*
The moose likes Beginning Java and the fly likes explicitly initialized variables Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Beginning Java
Bookmark "explicitly initialized variables" Watch "explicitly initialized variables" New topic
Author

explicitly initialized variables

Willie Toma
Ranch Hand

Joined: May 11, 2001
Posts: 78
How can a member(instance) variable be assigned a default value if not initialized explicitly.
Here is the question that I encountered:
T or F: Member(instance) variables are always assigned a default value if not explicitly initialized.
Answer: True
Member variables are always given a default value -- numerical primitives get zero, chars get '/u0000' and objet references get null.
Does anyone know of any examples?
sai challa
Ranch Hand

Joined: Feb 06, 2001
Posts: 54
I saw this material in JLS which might be of use to you.
Each class variable, instance variable, or array component is initialized with a default value when it is created :
1.For type byte, the default value is zero, that is, the value of (byte)0.
2.For type short, the default value is zero, that is, the value of (short)0.
3.For type int, the default value is zero, that is, 0.
4.For type long, the default value is zero, that is, 0L.
5.For type float, the default value is positive zero, that is, 0.0f.
6.For type double, the default value is positive zero, that is, 0.0d.
7.For type char, the default value is the null character, that is, '\u0000'.
8. For type boolean, the default value is false.
9.For all reference types (class types,interface types or arrays), the default value is null.
Example Program:
class Point
{
static int npoints;
int x, y;
Point root;
}
class Test
{
public static void main(String[] args)
{
System.out.println("npoints=" + Point.npoints);
Point p = new Point();
System.out.println("p.x=" + p.x + ", p.y=" + p.y);
System.out.println("p.root=" + p.root);
}
}
prints:
npoints=0
p.x=0, p.y=0
p.root=null
[This message has been edited by sai challa (edited May 11, 2001).]
[This message has been edited by sai challa (edited May 11, 2001).]
Cindy Glass
"The Hood"
Sheriff

Joined: Sep 29, 2000
Posts: 8521
Note that this is true for:
static variables (class variables)
instance variables
array components
method parameters
constructor parameters and
exception parameters
But it is NOT true for local variables which must be explicitely initialized.


"JavaRanch, where the deer and the Certified play" - David O'Meara
Val Dra
Ranch Hand

Joined: Jan 26, 2001
Posts: 439
parameters are local variables just a note.


Val SCJP <BR>going for SCJD
 
GeeCON Prague 2014
 
subject: explicitly initialized variables