• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

VARIABLE INITIALIZATION TIME

 
KRISH DOSS
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can any one explain me about variables initialization in java?.
A class has 20 instance(primitive) variables
and all variables have been explicitly assigned
their default values.
a). does it mean that these variables are initialized twice when instance of the class
is created?.
can anyone explain complete picture of what happens , when variables are explicitly declared/undeclared?
thanks
krishna
 
Peter Haggar
author
Ranch Hand
Posts: 106
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by KRISH DOSS:

a). does it mean that these variables are initialized twice when instance of the class
is created?.

Yes.
When memory is allocated for an object, all its statics and instance variables are initialized to their default values. That's null for references, false for booleans, and 0 for numerics. Therefore, if the code initializes these same variables to their default values in the constructor, or when they are declared, the initialization happens twice, unless the duplicate initialization is removed by a runtime optimizer. No javac compilers I have tried remove it. For example:

and

Both of these classes are inefficient and generate the same bytecode shown here:

The assignment of i and s do not need to occur, but there is bytecode to do so. Note that local variables have no default value and must be explicitly initialized.
Peter Haggar
 
KRISH DOSS
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Peter
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic