Multiple Static Blocks and Execution Order
What you'll learn: How multiple static blocks work together and the order in which Java executes them.
When a class contains more than one static block, you might wonder: which one runs first? The answer is beautifully simple: they execute in the exact order they appear in your source code, from top to bottom.
Think of static blocks like a recipe's preparation steps. If step 1 says "chop onions" and step 2 says "heat oil," you do them in that order. Java reads your class file the same way—top to bottom—and executes each static block as it encounters it.
Why Multiple Static Blocks?
You might split initialization logic into multiple static blocks for organization. Perhaps one block loads configuration, another validates it, and a third sets up resources. Each block runs once, in order, before any other code in your class can execute.
The Order Is Guaranteed
Java guarantees this top-to-bottom execution order. If staticBlock1 appears before staticBlock2 in your source file, staticBlock1 will always execute first. This happens during class loading, before any static methods are called or any instances are created.
public class Demo {
static int x;
static {
x = 10;
System.out.println("First block: x = " + x);
}
static {
x = x + 5;
System.out.println("Second block: x = " + x);
}
static {
x = x * 2;
System.out.println("Third block: x = " + x);
}
}
Output when the class loads:
First block: x = 10
Second block: x = 15
Third block: x = 30
Key Takeaway: Multiple static blocks execute sequentially in the order they appear in the source code, each running exactly once during class initialization.