Here is what happens in chronological order:
-
Class
B
contains the main-method so it is loaded by the class loader. -
Initialization of
B
referencesA
, so classA
is loaded. -
A
has a static variableX
initialized toB.Y + 1
.The initialization of
B.Y
hasn’t been executed yet, soB.Y
evaluates to 0, and thus 1 is assigned toA.X
-
Now
A
has finished loading, and the initialization ofB.Y
can take place.The value of
A.X + 1
(1 + 1) is assigned toB.Y
. -
The values of
A.X
andB.Y
are printed as1
and2
respectively.
Further reading:
Java Language Specification, ยง12.4.1 When Initialization Occurs