Sub topic 6
Static Blocks and Initialization Order
This chapter assumes you can write classes with fields, constructors, and methods. It also assumes you know what static means for a field and for a method, and you have seen basic inheritance. The chapter covers when Java runs static initialization code, in what order, and what goes wrong when that code fails.
Two kinds of initialization
Java initializes a class and the objects of that class at different times.
- Class initialization happens once per class, per class loader. It sets up static fields and runs static blocks.
- Instance initialization happens once per object. It sets up instance fields, runs instance blocks, and runs the constructor.
A static block is a block of code preceded by the static keyword, placed directly in the class body. It runs during class initialization. An instance block is the same thing without static. It runs at the start of every object construction.
Static blocks
You need a static block when a static field cannot be set with a single expression. The Config class below builds a map with several statements, then wraps it so callers cannot modify it.
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
public class Config {
public static final int MAX_USERS = 100;
public static final Map<String, Integer> LIMITS;
static {
Map<String, Integer> m = new HashMap<>();
m.put("free", 1);
m.put("pro", 10);
LIMITS = Collections.unmodifiableMap(m);
}
}LIMITS is declared static final but has no value at its declaration. This is legal because the compiler checks that the static block assigns it exactly once. The local variable m exists only inside the block, so the mutable map never leaks out.
A class may have several static blocks. They run in the order they appear in the source file.
When does a class get initialized?
A class is not initialized when the program starts or when it is first mentioned. The JVM initializes it lazily, the first time one of these things happens:
| Trigger | Example |
|---|---|
| An instance is created | `new Counter()` |
| A static method is called | `Counter.getCreated()` |
| A non-constant static field is read or assigned | `Counter.created = 5` |
| The class holds `main` and is launched | `java InitOrder` |
| Reflection loads and initializes it | `Class.forName("Counter")` |
| A subclass is initialized | `new Child()` initializes `Parent` first |
Some things do not trigger initialization. Declaring a variable of the type does not. Neither does reading a compile-time constant (covered below).
Order within one class
Static initializers run in textual order. Static field initializers and static blocks are treated as one sequence, from the top of the class to the bottom. Before any of them runs, every static field already holds its default value: 0, false, or null.
public class TextualOrder {
static int first = log("first", 1);
static {
System.out.println("block sees second = " + TextualOrder.second);
}
static int second = log("second", 2);
static int log(String name, int value) {
System.out.println("init " + name);
return value;
}
public static void main(String[] args) {
System.out.println(first + " " + second);
}
}The output is:
init first
block sees second = 0
init second
1 2The block runs before second is assigned, so it sees the default 0. The program reads second through TextualOrder.second on purpose. Reading it by its simple name, second, before its declaration is a compile error ("illegal forward reference"). The qualified name gets around that check, and you see the default value. Treat this as a trap to avoid, not a technique.
Instance initialization order
When you create an object, Java runs the instance field initializers and instance blocks in textual order, then the rest of the constructor body. Static blocks are not part of this. They already ran when the class was initialized.
public class InitOrder {
static {
System.out.println("1: static block");
}
{
System.out.println("2: instance block");
}
public InitOrder() {
System.out.println("3: constructor");
}
public static void main(String[] args) {
System.out.println("main");
new InitOrder();
new InitOrder();
}
}The output is:
1: static block
main
2: instance block
3: constructor
2: instance block
3: constructorInitOrder contains main, so the JVM initializes it before calling main. That is why the static block prints first. The instance block and constructor run once for each new.
Order with inheritance
With a superclass, the rule is: the superclass is initialized before the subclass, and the superclass constructor finishes before the subclass instance code starts.
class Parent {
static {
System.out.println("Parent static");
}
{
System.out.println("Parent instance");
}
Parent() {
System.out.println("Parent constructor");
}
}
class Child extends Parent {
static {
System.out.println("Child static");
}
{
System.out.println("Child instance");
}
Child() {
System.out.println("Child constructor");
}
}
public class InheritanceOrder {
public static void main(String[] args) {
System.out.println("start");
new Child();
System.out.println("again");
new Child();
}
}The output is:
start
Parent static
Child static
Parent instance
Parent constructor
Child instance
Child constructor
again
Parent instance
Parent constructor
Child instance
Child constructorThe first new Child() triggers class initialization of Parent, then Child. The second new Child() skips both static blocks, because each class is initialized only once.
Common errors and gotchas
Exceptions in static initializers
A static initializer cannot throw a checked exception. If it throws an unchecked one, the JVM wraps it in an ExceptionInInitializerError. The class is then marked as failed. Every later attempt to use it throws NoClassDefFoundError.
class Risky {
static int value = Integer.parseInt("x");
static void touch() {
}
}
public class FailedInit {
public static void main(String[] args) {
try {
Risky.touch();
} catch (ExceptionInInitializerError e) {
System.out.println("cause: " + e.getCause());
}
try {
Risky.touch();
} catch (NoClassDefFoundError e) {
System.out.println("second attempt: NoClassDefFoundError");
}
}
}The output is:
cause: java.lang.NumberFormatException: For input string: "x"
second attempt: NoClassDefFoundErrorThe second error often confuses people. Its message says the class could not be initialized, but the real problem is in the stack trace of the first failure. When you see NoClassDefFoundError for a class that is definitely on the classpath, search the logs for an earlier ExceptionInInitializerError.
Compile-time constants do not trigger initialization
A static final field of a primitive or String type that is set from a constant expression is a constant variable. The compiler copies its value into every place that uses it. Reading it never initializes the class.
class Limits {
static final int MAX = 5;
static final int RUNTIME_MAX = Integer.parseInt("5");
static {
System.out.println("Limits initialized");
}
}
public class ConstantDemo {
public static void main(String[] args) {
System.out.println(Limits.MAX);
System.out.println("before runtime constant");
System.out.println(Limits.RUNTIME_MAX);
}
}The output is:
5
before runtime constant
Limits initialized
5MAX is a constant variable, so its read is inlined and Limits stays uninitialized. RUNTIME_MAX needs a method call, so reading it forces initialization. Inlining has a second consequence. If you change MAX and recompile only Limits, other classes keep the old value until you recompile them as well.
Other pitfalls
- Forward references. A simple-name read of a static field before its declaration is a compile error, but a write is allowed. Reordering declarations can change behavior without any compiler warning.
- Circular dependencies. If class
A's static initializer uses classB, andB's usesA, one of them sees the other half-initialized, with default values in some fields. Break the cycle by moving shared state into a third class. - Overridable calls from constructors. A superclass constructor that calls an overridable method runs the subclass version before the subclass instance fields are initialized. The method sees
0ornullfor fields it expects to be set. - Heavy work in static blocks. Network calls, file reads, and large computations run on whichever thread first touches the class, and a failure there poisons the class for the rest of the run. Prefer explicit initialization methods for anything that can fail.
- Threads. The JVM guarantees that class initialization runs once and that other threads wait for it to finish. This makes a static
finalfield assigned in a static block safely published to all threads. Two classes that initialize each other from different threads can still deadlock.
A checklist for predicting output
- Find the first class that is used. Is it initialized yet? If not, initialize its superclass chain first, from the top.
- Within each class, run static field initializers and static blocks in textual order.
- For each
new, run the superclass constructor chain first. In each class, run instance initializers in textual order, then the rest of the constructor body. - Remember that static code runs once per class, and instance code runs once per object.
Exercise
What does this program print, line by line? class Base { static { System.out.println("A"); } { System.out.println("B"); } Base() { System.out.println("C"); } } class Derived extends Base { static { System.out.println("D"); } { System.out.println("E"); } Derived() { System.out.println("F"); } } public class Quiz { public static void main(String[] args) { System.out.println("G"); new Derived(); new Derived(); } }
Show answer
G, A, D, B, C, E, F, B, C, E, F. "G" prints first because Quiz has no static blocks, so main starts immediately. The first new Derived() initializes Base ("A") and then Derived ("D"). It then runs Base's instance block ("B") and constructor ("C"), then Derived's instance block ("E") and constructor ("F"). The second new Derived() skips both static blocks and repeats B, C, E, F.
Exercise
A class has static final int SIZE = 10; and a static block that prints "loaded". Another class prints Holder.SIZE and nothing else. Does "loaded" appear? What changes if the field is static final int SIZE = compute();?
Show answer
"loaded" does not appear. SIZE is a compile-time constant variable, so its value is inlined into the caller and Holder is never initialized. With compute() the field is no longer a constant expression. Reading it initializes Holder, so the static block runs and prints "loaded" before the value is read.