In what order do static blocks, instance blocks and constructors run in Java?
A static block runs once when the class is first loaded. For every new object, instance initialiser blocks and field initialisers run first, in source order, and then the constructor body.
Explain it simply
Opening a new shop: the building is constructed once (static block). Then for every customer, the counter is wiped and the till is set up (instance block) before the shopkeeper greets them (constructor).
Example
class Demo {
static { System.out.println("static block"); }
{ System.out.println("instance block"); }
Demo() { System.out.println("constructor"); }
}
new Demo();
new Demo();
// prints:
// static block
// instance block
// constructor
// instance block
// constructorWhat to say in the interview
"On first use of the class, the JVM loads it and runs static initialisers and static field initialisers in textual order, once. Each time I create an object, the parent constructor chain runs first. Within each class, instance field initialisers and instance blocks run in source order, before the constructor body. With inheritance, the full order is: parent static, child static, parent instance and constructor, child instance and constructor."
Common mistakes
- Thinking the static block runs every time an object is created.
- Forgetting that the parent's constructor runs before the child's instance blocks.