Sub topic 6
Static Blocks and Initialization Order
Assume you know how to define classes, create objects with new, and use constructors. This chapter focuses on what Java runs before and during object creation.
A static block is a block of code that runs once when Java initializes a class. It is useful when a static field needs more setup than a single expression can provide.
When a Class Is Initialized
Java initializes a class before its first active use. Common triggers include:
- Calling a static method.
- Reading a non-constant static field.
- Creating the first object with
new. - Loading the class through certain reflection operations.
During class initialization, Java processes static field initializers and static blocks from top to bottom. This order follows their position in the source file.
public class Startup {
private static int value = announce("static field");
static {
announce("static block");
}
{
announce("instance block");
}
public Startup() {
announce("constructor");
}
private static int announce(String message) {
System.out.println(message);
return 42;
}
public static void main(String[] args) {
System.out.println("main");
new Startup();
new Startup();
}
}The output is:
static field
static block
main
instance block
constructor
instance block
constructorThe class is initialized before Java starts executing the body of main. The static field initializer runs first because it appears before the static block.
The instance initializer and constructor run each time an object is created. Therefore, they run twice in this example. The static code runs only once.
Static Blocks for Complex Setup
Use a static block when a static value requires several statements or error handling. The field should usually be final if callers must not replace the reference.
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
public final class Plans {
public static final Map<String, Integer> LIMITS;
static {
Map<String, Integer> limits = new HashMap<>();
limits.put("free", 1);
limits.put("pro", 10);
LIMITS = Collections.unmodifiableMap(limits);
}
private Plans() {
}
}The temporary limits map is built inside the block. The public field receives an unmodifiable view, so callers cannot add or remove entries through Plans.LIMITS.
A static block cannot use this, because no object exists during class initialization. It can use other static members that have already been initialized. Be careful with the order of declarations: a static block that depends on a field should normally appear after that field has been assigned.
Class Initialization and Inheritance
When a subclass is initialized, Java initializes its superclass first. The usual order is:
- Superclass static fields and static blocks.
- Subclass static fields and static blocks.
- Superclass instance fields, instance blocks, and constructor.
- Subclass instance fields, instance blocks, and constructor.
A static block that throws an exception prevents successful class initialization. Java commonly reports this as an ExceptionInInitializerError. Keep static setup small and predictable, especially when it performs file, network, or database work.
Exercise
In the Startup example, how many times does the static block run, and how many times does the constructor run?
Show answer
The static block runs once when the class is initialized. The constructor runs twice because the program creates two Startup objects.