This week's book giveaways are in the Java EE and JavaScript forums.
We're giving away four copies each of The Java EE 7 Tutorial Volume 1 or Volume 2(winners choice) and jQuery UI in Action and have the authors on-line!
See this thread and this one for details.
The moose likes Performance and the fly likes VARIABLE INITIALIZATION TIME Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Java » Performance
Bookmark "VARIABLE INITIALIZATION TIME" Watch "VARIABLE INITIALIZATION TIME" New topic
Author

VARIABLE INITIALIZATION TIME

KRISH DOSS
Greenhorn

Joined: Feb 16, 2002
Posts: 19
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

Joined: Jan 03, 2001
Posts: 106
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


Senior Software Engineer, IBM
author of: Practical Java
KRISH DOSS
Greenhorn

Joined: Feb 16, 2002
Posts: 19
Thanks Peter
 
 
subject: VARIABLE INITIALIZATION TIME