for the following code:
class A
{
public static int X;
static { X = B.Y + 1;}
}
public class B
{
public static int Y = A.X + 1;
static {}
public static void main(String[] args) {
System.out.println("X = "+A.X+", Y = "+B.Y);
}
}
the output is:
X = 1, Y = 2
Why? And How?
P.S: Code snippet taken from JavaCamp.org
Here is what happens in chronological order:
Class
Bcontains the main-method so it is loaded by the class loader.Initialization of
BreferencesA, so classAis loaded.Ahas a static variableXinitialized toB.Y + 1.The initialization of
B.Yhasn’t been executed yet, soB.Yevaluates to 0, and thus 1 is assigned toA.XNow
Ahas finished loading, and the initialization ofB.Ycan take place.The value of
A.X + 1(1 + 1) is assigned toB.Y.The values of
A.XandB.Yare printed as1and2respectively.Further reading:
Java Language Specification, §12.4.1 When Initialization Occurs