• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

explicitly initialized variables

 
Willie Toma
Ranch Hand
Posts: 78
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 54
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 8521
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Val Dra
Ranch Hand
Posts: 439
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
parameters are local variables just a note.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic