When Static Blocks Execute
What you'll learn: You'll understand exactly when static blocks run — once, automatically, the instant the JVM loads your class.
The Class Loading Trigger
Static blocks execute exactly once, at the moment the JVM first loads the class into memory. This happens automatically, without you explicitly calling anything. Once the class is loaded, the static block never runs again during that program's execution.
Think of it like a building's grand opening ceremony. The ribbon-cutting happens once, the first time the building opens to the public — not every time someone walks through the door afterward.
What Triggers Class Loading?
The JVM loads a class (and runs its static blocks) when:
- You create the first instance of the class with
new - You access any static field or method of the class
- You reference the class in certain other ways (like using reflection)
Importantly, the static block runs before any constructors execute and before any static methods are called. It's the JVM's way of saying, "Let me set up this class properly before anyone uses it."
Example Timeline
public class Counter {
static int total;
static {
total = 100;
System.out.println("Static block executed");
}
}
// Meanwhile, in another class:
System.out.println("Program started");
int value = Counter.total; // Class loads HERE — static block runs
System.out.println(value);
Counter c = new Counter(); // Static block does NOT run again
Output:
Program started
Static block executed
100
The static block fired the instant we touched Counter.total, not when we ran new Counter().
Key Takeaway: Static blocks execute exactly once when the JVM first loads the class — before any constructors run and before any static members are accessed.