Static Circular Dependency in Java

Here is what happens in chronological order:

  1. Class B contains the main-method so it is loaded by the class loader.

  2. Initialization of B references A, so class A is loaded.

  3. A has a static variable X initialized to B.Y + 1.

    The initialization of B.Y hasn’t been executed yet, so B.Y evaluates to 0, and thus 1 is assigned to A.X

  4. Now A has finished loading, and the initialization of B.Y can take place.

    The value of A.X + 1 (1 + 1) is assigned to B.Y.

  5. The values of A.X and B.Y are printed as 1 and 2 respectively.

Further reading:

Java Language Specification, ยง12.4.1 When Initialization Occurs

Leave a Comment