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
xoryfinal 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.