Complete Explanation
The order of execution is like,
- static block
- instance block
- constructor
Explanation
Static block will always be called only once in the very beginning whenever the class is accessed by any means, in your case which is when you run the program. (That is what static block is meant for). It does not depend on instances therefore not called again when new instances are created.
Then the Instance initialization block will be called for each instance created and after that the constructor for each instance created. Because both of them can be used to instantiate the instance.
Is instance initialization block actually called before constructor?
After compilation the code will become,
public class Test {
Test(){
super();
System.out.println("2");
System.out.println("1");
}
static {
System.out.println("3");
}
public static void main(String args[]) {
new Test();
}
}
So you can see, the statement written in instance block itself becomes part of the constructor. Therefore it is executed before the statements already written in the constructor.
From this documentation
The Java compiler copies initializer blocks into every constructor. Therefore, this approach can be used to share a block of code between multiple constructors.