OCP exam prep: initialization order¶
☕ Java 17 · 🎓 OCP 1Z0-829 · The Order Java Builds Your Objects In
Optional page
This page is for readers preparing the Oracle Certified Professional Java SE 17 Developer exam (1Z0-829). The concepts are all you need otherwise.
Exam objective: Create classes and records, and define and use instance and static fields and methods, constructors, and instance and static initializers.
Four traps to watch for¶
Trap 1 — Static runs once
Static blocks run once per class, however many objects are created. Count the new calls, but print static output only once.
Trap 2 — Top to bottom
Fields and initializer blocks run in file order, all before the constructor body. Static code written below instance code still runs first.
Trap 3 — Final: exactly once
Every constructor must leave each final field assigned once: on the declaration, in an instance block, or in the constructor. Never twice, never zero times.
Trap 4 — Follow the real path
Only constructors actually called run. Start from the new call and trace every this() and super() before writing any output.
Practice questions¶
print stands for System.out.print.
1. What does this program print?
class Content { static { print("A"); } { print("B"); } Content() { print("C"); } }
class Series extends Content { static { print("D"); } { print("E"); } Series() { print("F"); } }
// main: new Series(); new Series();
A. ABCDEFBCEF
B. ADBCEFBCEF
C. ADBCEFADBCEF
D. ADEFBCEFBC
Answer
B. Classes first, parent first, once: A D. Each object: Content part B C, then Series part E F. The second object skips the static blocks: B C E F.
2. Which line or lines fail to compile?
1: public class Subscription {
2: private final String plan;
3: private final int screens = 2;
4: public Subscription(String p) { plan = p; }
5: public Subscription() { screens = 4; } }
A. Line 4 only
B. Line 5 only
C. Lines 3 and 5
D. It compiles
Answer
B. Line 5 assigns screens a second time and never assigns plan. Lines 3 and 4 each assign a final field once.
3. What is the output?
public class Catalog {
static { System.out.print("load-"); }
Catalog() { System.out.print("new-"); }
public static void main(String[] args) {
System.out.print("start-"); new Catalog(); new Catalog();
}
}
A. start-load-new-new-
B. load-start-new-new-
C. load-start-new-load-new-
D. start-new-new-load-
Answer
B. main is in Catalog, so the class is set up before main runs: load- comes first. Static code runs once, the constructor twice.