Java Initialization Order and final Fields (OCP 21)
Java initialization order for the OCP 21 exam: when a class is initialized and when it isn't, static and instance initializers in source order, parent-first object construction, final and static final fields assigned exactly once, forward references, and the overridable-method trap.
kvi5hnuCode Sprout team member10 min readOn this page
Article 4 introduced initializer blocks with a single class. With inheritance, the exam combines static blocks, instance blocks, field declarations and chained constructors, and then asks what the program prints. This article gives you an exact procedure for those questions, plus the rules for final fields.
Phase 1: initializing a class
Before a class is used, the JVM initializes it once. Initializing class X means:
- Initialize
X's superclass first, if it hasn't been initialized yet. This repeats all the way up toObject. - Run
X's static variable initializers andstatic { }blocks together, in the order they appear in the source file.
Some books list "all static variables, then all static blocks". The real rule is plain top-to-bottom order, and that's what the exam's code relies on:
public class Order {
static int a = p("a ");
static { System.out.print("s1 "); }
static int b = p("b ");
static int p(String s) { System.out.print(s); return 1; }
public static void main(String[] args) { System.out.println("main"); }
}
// prints: a s1 b main
The most important rule is that a class is initialized at most once, no matter how many objects you create:
class Animal { static { System.out.print("A"); } }
public class Wombat extends Animal {
static { System.out.print("B"); }
public static void main(String[] args) {
System.out.print("C");
new Wombat();
new Wombat();
}
}
// prints: ABC
Wombat contains main, so the JVM must initialize it before main can run. That initializes Animal first (A), then Wombat (B), and only then does main print C. If main lived in some other class, Wombat wouldn't be initialized until its first use, so that version would print CAB.
What triggers class initialization
A class is initialized just before the first of these happens:
- an instance is created with
new - a static method is called
- a static field is read or assigned, unless it's a compile-time constant
- a subclass is initialized
- it's the class that holds
main
Some uses don't trigger initialization. The exam rarely tests these, but they explain surprising output:
class Hive {
static final int MAX = 5; // compile-time constant: copied into callers
static final Integer BOXED = 6; // not a constant (Integer isn't primitive/String)
static { System.out.print("[Hive init]"); }
}
class Parent { static int shared = 1; static { System.out.print("[Parent init]"); } }
class Child extends Parent { static { System.out.print("[Child init]"); } }
System.out.print(Hive.MAX + " "); // 5 — Hive not initialized
System.out.print(Child.shared + " "); // [Parent init]1 — only Parent: the field lives there
Hive[] cells = new Hive[3]; // nothing — an array doesn't initialize Hive
System.out.print(Hive.BOXED + " "); // [Hive init]6
Phase 2: initializing an object
Each time new X(...) runs:
- Initialize class
Xif that hasn't happened yet (Phase 1). - Follow the constructor's first statement up the hierarchy.
this(...)stays in the same class, andsuper(...)(written or inserted) moves to the parent. This repeats untilObject(). - Then, starting from the top class and working down, each class does two things:
- runs its instance variable initializers and
{ }blocks, together, in source order - runs its constructor bodies, starting with the innermost
this(...)target and unwinding outward
- runs its instance variable initializers and

The key detail in step 3 is that a class's instance initializers run after its parent's constructor body has finished, and before its own constructor body. They run once per object, even when the constructors chain with this(). Calling this(...) doesn't run the initializers twice.
A worked example without inheritance
public class Ticket {
private String venue = "Riverside";
{ System.out.print(venue + "-"); }
private static int sold = 0;
static { System.out.print(sold + "-"); }
{ sold++; System.out.print(sold + "-"); }
public Ticket() { System.out.print("t"); }
public static void main(String[] args) {
System.out.print("go-");
new Ticket();
}
}
Work it out in order:
- Class: the only static members are
sold = 0and the static block, which prints0-. main: printsgo-.- Instance, source order:
venueis set, its block printsRiverside-, and the next block incrementssoldand prints1-. - Constructor body: prints
t.
Output: 0-go-Riverside-1-t
The static field sold sits below the first instance block in the file, but statics always run first, because they belong to Phase 1.
A worked example with inheritance and this()
class Instrument {
static { System.out.print("1"); }
{ System.out.print("2"); }
Instrument(String name) { this(7); System.out.print("3"); }
Instrument() { System.out.print("4"); }
Instrument(int strings) { System.out.print("5"); }
}
public class Cello extends Instrument {
static { System.out.print("6"); }
Cello(int size) { super("cello"); System.out.print("7"); }
{ System.out.print("8"); }
public static void main(String[] args) {
new Cello(4);
System.out.println();
new Cello(3);
}
}
Trace the first new Cello(4):
| Step | What happens | Prints |
|---|---|---|
| Class init | Instrument statics, then Cello statics | 1 6 |
| Call chain | Cello(int) → Instrument(String) → Instrument(int) → Object() | (nothing yet) |
Instrument part | instance block, then the bodies unwind: Instrument(int), then Instrument(String) | 2 5 3 |
Cello part | instance block (even though it's written after the constructor), then the Cello(int) body | 8 7 |
The second new Cello(3) skips class initialization, so the output is:
1625387
25387
The first line starts with 16 (the statics) and the second line doesn't. Instrument() never runs, so 4 never prints.
final fields: assigned exactly once
A non-final field that isn't assigned gets a default value (0, false, null, …). A final field never gets a usable default. The compiler requires it to be definitely assigned exactly once.
| Kind of field | Where it can be assigned |
|---|---|
static final | in its declaration, or in one static { } block |
final instance field | in its declaration, or in an instance { } block, or in every constructor |
A final field with no initializer in its declaration is called a blank final.
public class Locker {
private final int size;
private final String owner;
private final String brand = "Acme"; // declaration
{ size = 30; } // instance initializer
public Locker(String owner) { this.owner = owner; } // compiles
public Locker() { } // DOES NOT COMPILE: owner never assigned
public Locker(int s) { this.size = s; this.owner = "x"; } // DOES NOT COMPILE: size already assigned
}
The compiler checks each constructor on its own, so both broken constructors fail. javac reports "variable owner might not have been initialized" and "variable size might already have been assigned". The fix for Locker() is to delegate:
public Locker() { this(null); } // compiles: Locker(String) assigns owner
A constructor that starts with this(...) doesn't need to assign anything, because the constructor it delegates to already did. null is a perfectly good value for a final reference. The rule is that the field is assigned, not that it's non-null.
The compiler does flow analysis, so branches count:
final int level;
Gauge(boolean high) { if (high) level = 9; else level = 1; } // compiles: assigned on both paths
Gauge(int x) { if (x > 0) level = x; } // DOES NOT COMPILE: not assigned when x <= 0
Gauge() { for (int i = 0; i < 1; i++) level = 1; } // DOES NOT COMPILE: "might be assigned in loop"
static final fields follow the class rules: a static block can assign one, but a constructor or instance block can't. Either of those fails with "cannot assign a value to static final variable". A static final field that's never assigned also fails to compile.
You can't read a blank final field before it's assigned, even through this.level, from an instance block or a lambda in a field initializer. javac reports "variable level might not have been initialized".
Forward references
Because initializers run top to bottom, the compiler stops a field's initializer from reading a field declared below it by simple name:
int a = b + 1; // DOES NOT COMPILE: illegal forward reference
int b = 1;
{ System.out.println(c); } // DOES NOT COMPILE: illegal forward reference
int c = 1;
There are two loopholes. They're legal, but they show default values:
{ d = 5; } // assigning a later field is allowed
int d = 1; // ...but this runs afterwards: d ends up 1
int e = this.f + 1; // qualified name is allowed: f is still 0, so e is 1
int f = 1;
The same rules apply to static fields. static int a = b; with b declared later doesn't compile, and static int a = Order.b; compiles and reads 0.
The overridable-method trap
A parent constructor can call a method that the child overrides. The child's version runs before the child's field initializers have run:
class Gadget {
Gadget() { describe(); }
void describe() { }
}
class Phone extends Gadget {
final int keys = 7; // compile-time constant: already "set"
int apps = 9; // runs after Gadget() finishes
String name = "pocket";
@Override void describe() { System.out.println(keys + " " + apps + " " + name); }
}
new Phone(); // prints: 7 0 null
keys prints 7 because a final field initialized with a constant expression is inlined as a constant. apps and name still hold their defaults. Since JDK 21, javac -Xlint:this-escape warns about this pattern in public, extensible classes. The usual fix is to call only private, static or final methods from constructors.
What's current
- The initialization order and
finalfield rules are unchanged through Java 25. - Java 25's flexible constructor bodies allow assigning fields before
super(...), but only fields declared in the class itself and only if their declaration has no initializer (article 32).
Exam traps from this article
A complete example
This program logs each initialization step for a two-level hierarchy, creates two trucks, and shows that the static steps happen only once and that reading a constant initializes nothing.
import java.util.ArrayList;
import java.util.List;
public class Solution {
static final List<String> LOG = new ArrayList<>();
static String note(String step) {
LOG.add(step);
return step;
}
static class Vehicle {
static final int WHEELS = 4; // compile-time constant
static String plant = note("Vehicle static field");
static int built; // default 0
static { note("Vehicle static block"); }
final String vin; // blank final
String color = note("Vehicle field");
{ note("Vehicle instance block"); }
Vehicle(String vin) {
this.vin = vin;
built++;
note("Vehicle(String) body");
}
}
static class Truck extends Vehicle {
static { note("Truck static block"); }
final int axles;
{ note("Truck instance block"); }
String cargo = "empty";
Truck(int axles) {
super("TRK-" + axles);
this.axles = axles;
note("Truck(int) body");
}
Truck() {
this(2); // runs Truck(int) first
note("Truck() body");
}
}
static void show(String heading) {
System.out.println(heading);
for (String step : LOG) System.out.println(" " + step);
LOG.clear();
}
public static void main(String[] args) {
System.out.println("Vehicle.WHEELS = " + Vehicle.WHEELS);
show("After reading a constant (no class initialized):");
Truck first = new Truck();
show("First new Truck():");
Truck second = new Truck(6);
show("Second new Truck(6) (statics already done):");
System.out.println(first.vin + " axles=" + first.axles + " cargo=" + first.cargo);
System.out.println(second.vin + " axles=" + second.axles);
System.out.println("Vehicle.built = " + Vehicle.built);
}
}
Output:
Vehicle.WHEELS = 4
After reading a constant (no class initialized):
First new Truck():
Vehicle static field
Vehicle static block
Truck static block
Vehicle field
Vehicle instance block
Vehicle(String) body
Truck instance block
Truck(int) body
Truck() body
Second new Truck(6) (statics already done):
Vehicle field
Vehicle instance block
Vehicle(String) body
Truck instance block
Truck(int) body
TRK-2 axles=2 cargo=empty
TRK-6 axles=6
Vehicle.built = 2
Points to notice:
Vehicle.WHEELSis a compile-time constant, so reading it logs nothing. Neither class has been initialized yet at that point.- The first
new Truck()logs the static steps parent-first, then each class's instance initializers before its constructor bodies. Truck()delegates withthis(2). TheTruck(int)body runs before theTruck()body, and the Truck instance block runs only once.- The second truck repeats only the instance steps.
vinandaxlesare blank finals, each assigned exactly once by a constructor.
Common questions
Is it "all static fields, then all static blocks"? No. Static field initializers and static blocks run together in the order they're written, and the same goes for instance fields and instance blocks. Exam code usually gives the same result either way, but source order is the real rule.
When exactly is a class initialized if main is elsewhere?
Lazily, just before its first active use (new, a static method call, or a non-constant static field access). For exam purposes: before first use, and only once.
Can a final field be reassigned in a setter?
No. Assigning a final field outside an initializer or constructor never compiles.
Does final make the object immutable?
No. A final reference can't be repointed, but the object it refers to can still change. Article 36 covers immutable classes.
Summary
- Class initialization happens once, parent first: static fields and static blocks in source order.
- Object creation follows the constructor chain up to
Object, then, for each class from the top down, runs its instance fields and blocks in source order and then its constructor bodies. finalinstance fields must be assigned exactly once: in the declaration, an instance block, or every constructor (constructors that start withthis(...)are exempt).static finalfields must be assigned in the declaration or a static block.- Forward references by simple name don't compile. Overridable calls from a parent constructor see the child's defaults.
Practice quiz
Test yourself with the initialization order quiz: 10 exam-style questions with explanations.
Previous: Java Constructors: Default Constructor, this() and super() (OCP 21)
Next: Java Method Overriding and Hiding: Rules, final Methods and Static Hiding (OCP 21)
Related reading
- Java Constructors: Default Constructor, this() and super() (OCP 21)
- Java Inheritance and Class Modifiers: extends, Object, this and super (OCP 21)
- Java Method Overloading and Overload Resolution (OCP 21)
- Java Pass-by-Value, Returning Objects and Autoboxing (OCP 21)
- Java static Members, Static Initializers and Static Imports (OCP 21)

More in OCP Java 21
OCP Java 21 Mock Exam 3 (1Z0-830)
The third full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), weighted toward the hardest areas: streams, concurrency, generics, modules and I/O. 120 minutes, 68% to pass, with explanations.
OCP Java 21 Mock Exam 2 (1Z0-830)
The second full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830): new questions on every objective, with more multi-select. 120 minutes, 68% to pass, with an explanation for every answer.
OCP Java 21 Mock Exam 1 (1Z0-830)
A full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), covering every objective at exam difficulty. 120 minutes, 68% to pass, with an explanation for every answer.
Quiz: Final Review (OCP 21)
Ten exam-style questions mixing the most-tested OCP Java 21 rules from the final checklist: promotion, String immutability, overloading, initialization order, collections, streams, exceptions and switch patterns, with explanations.
Discussion
Sign in to ask a question or share what you learned.