v2
is null when it enters A\'s c\'tor at the first time, but if I put v2
\'s declaration & initialization before instance
it will h
The static variables are initialized in the order they appear in the source file when class A is initialized (before main
is executed).
A c'tor v1 [ab] v2 [null]
since its initialization involves creating an instance of A) - it is initialized before v2
, which is why v2
is still null
.After they are initialized, the main
method is executed, and produces the next 3 output lines. The creation of the new instance of A
inside the main
method produces a different output than the previous constructor call, since at this point both v1
and v2
are initialized.
EDIT :
Regarding your updated question :
If you follow the initialization procedure in JLS 12.4.2:
- Otherwise, record the fact that initialization of the Class object for C is in progress by the current thread, and release LC. Then, initialize the final class variables and fields of interfaces whose values are compile-time constant expressions.
...
- Next, execute either the class variable initializers and static initializers of the class, or the field initializers of the interface, in textual order, as though they were a single block.
As you can see, the final static variables whose values are compile-time constant expressions are initialized before the rest of the static variables. Therefore changing the value of v2
to the constant "ab"
causes v2
to be initialized before the instance
variable, which explains the different output.