In what exact order do static initializer blocks, instance initializer blocks and constructors run in Java?
The order is fixed, and it is worth knowing exactly.
First, the static parts of the class run once, when the class is first used. That means the static fields with their initial values, and the static initializer blocks, in the order they are written in the file.
Then, every single time you create an object, three things happen in this order. The instance fields with their initial values are set. Then the instance initializer blocks run, in the order they are written. And then the body of the constructor runs.
public class Main {
public static void main(String[] args) {
System.out.println("--- touching Counter.MAX triggers the class being loaded ---");
int max = Counter.MAX;
System.out.println("--- now making an object ---");
Counter counter = new Counter();
System.out.println("counter : " + counter.getValue());
}
}
class Counter {
static final int MAX = 100;
static {
System.out.println("static block ran");
}
private int value = 1;
{
System.out.println("instance block ran");
this.value = this.value + 10;
}
Counter() {
System.out.println("constructor ran");
this.value = this.value + 100;
}
int getValue() {
return this.value;
}
}
The output tells you the whole story. The static block runs once, the first time the class is touched. Then the instance block runs, and then the constructor body runs, every single time an object is made. The value ends up at 111, because it started at 1, the instance block added 10, and the constructor added 100.
The next question in this topic looks at why the instance block runs before the constructor body.