0

Following codes, why the print result is ABA. In my opinion, JVM will loads static block statements at first, then loads other statements, so B will print at first.

public class Test{

    public static Test test = new Test();
    {
        System.out.println("A");
    }
    static {
        System.out.println("B");
    }

    public static void main(String[] args) {
        Test test = new Test();
    }    

}
Mark Rotteveel
  • 82,132
  • 136
  • 114
  • 158

2 Answers2

0

This is because statics are processed in order. When you change it to:

class Test {
    static {
        System.out.println("B");
    }

    public static Test test = new Test();
    {
        System.out.println("A");
    }

    public static void main(String[] args) {
        Test test = new Test();
    }

}

You will get BAA.

The JVM will only initialize static once per class (and per ClassLoader if I am not mistaken), like I said in order. It would look something like this:

  1. new Test()
  2. detects Test is uninitialized
  3. initialize static vars in order
  4. picks up first: public static Test test = new Test();
  5. after iniating Test it will trigger the initialization block (println("A")). it will not trigger static {}, because it is already in a state for processing statics
  6. once Test is created and assigned, then it can pick up next block
  7. processes static {}
Albert Bos
  • 1,793
  • 1
  • 10
  • 24
0

The JVM first loads the class Test for running the main method. While loading, it assigns the memory and a default value (null) to the test variable.

After loading, the initializers are run in the top-down fashion.

At first, test = new Test() is run, which calls the default constructor of Test class containing the code of instance block (System.out.println("A")). Thus, we get A as output.

Then, the static block is executed which prints B.

After that, main method starts, where again default constructor of Test is called, which prints A.

Hence, the output ABA.