Order of Initialization: Static vs Instance
You'll learn the complete sequence Java follows when initializing static and instance components, ensuring you understand what runs when.
When you create an object in Java, initialization happens in a precise, predictable order. Understanding this sequence prevents confusion about when values are set and code executes.
The Complete Initialization Sequence
Think of class initialization like preparing a factory before making products. The factory setup (static) happens once, then each product (instance) goes through its own assembly line.
When a class is first loaded:
- Static field initializers (in order of declaration)
- Static blocks (in order of appearance)
When each object is created:
- Instance field initializers (in order of declaration)
- Instance initializer blocks (in order of appearance)
- Constructor body
The Critical Rule: Static Before Instance
Static initialization happens once per class when the class is first loaded by the JVM. Instance initialization happens every time you create an object, and only after static initialization is complete.
public class Demo {
static int classCounter = 0; // 1. Static field (once)
static { // 2. Static block (once)
System.out.println("Class loaded");
}
int id = ++classCounter; // 3. Instance field (per object)
{ // 4. Instance block (per object)
System.out.println("Instance block");
}
public Demo() { // 5. Constructor (per object)
System.out.println("Constructor for id: " + id);
}
}
When you first use Demo, you'll see "Class loaded" once. Each new Demo() then triggers the instance field, block, and constructor in sequence.
Key Takeaway: Java initializes classes in two phases: static members run once when the class loads, then instance members run for each object creation—fields first, then blocks, finally constructors.