Possible Duplicate:
Java static class initialization
Why is the string variable updated in the initialization block and not the integer(even though the block is written first)
class NewClass
{
static
{
System.out.println(NewClass.string+" "+NewClass.integer);
}
final static String string="static";
final static Integer integer=1;
public static void main(String [] args)//throws Exception
{
}
}
My output is
static null
P.S:Also noticed that string variable initialization happens before the block only when i insert the final modifier. why is that?why not for integer as well?I have declared it as final static too
From section 12.4.2 of the JLS, snipped appropriately:
So for non-compile-time-constants, it's not a case of "all variables" and then "all static initializers" or vice versa - it's all of them together, in textual order. So if you had:
Then the output would be:
Even making
x
ory
final wouldn't affect this here, as they still wouldn't be compile-time constants.At that point, it's a compile-time constant, and any uses of it basically inlined. Additionally, the variable value is assigned before the rest of the initializers, as above.
Section 15.28 of the JLS defines compile-time constants - it includes all primitive values and
String
, but not the wrapper types such asInteger
.They are initialized in the given order (fields and static blocks), that's why printed value is
null
, nothing was assigned to static fields that are defined after the static block.Here is a short and straight forward answer to you question....
static Variable
:static Variables are executed when the
JVM
loads theClass
, and theClass
gets loaded when either its been instantiated or itsstatic method
is being called.static Block or static Initializer Block
:static static Initializer Block gets Initialized before the
Class
gets instantiated or before itsstatic method
is called, and Even before itsstatic variable
is used.///////// Edited Part /////////
The above will print
static 1
.The reason is that the
JVM
will do the optimization process known asConstant folding
, doing an pre-calculation of the constant variables.Moreover in your case the result was
static null
causeConstant folding
is applied to Primitive type and not Wrapper Object, in your case its Integer...