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
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:
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