Memra

Initialization order: static, instance, and constructor

◈ 4 cards

The precise order Java initialises a class — and how to trace it on exam questions.

When does each piece of code run?

Java guarantees a specific initialisation order that the OCP exam tests directly:

  1. Static fields and static initialiser blocks — run once, when the class is first loaded by the JVM, in textual order.
  2. Instance fields and instance initialiser blocks — run on every new, in textual order, before the constructor body.
  3. Constructor body — runs last.
public class Sequence {
    static int classCount;
    static { classCount = 1; System.out.println("static block"); }

    int id = ++classCount;
    { System.out.println("instance block"); }

    Sequence() { System.out.println("constructor"); }
}

new Sequence();
new Sequence();

Output:

static block
instance block
constructor
instance block
constructor

The static block fires once at class load. On each new: instance block, then constructor — never the static block again.

static blockclass load — once onlyinstance blockfirst new Sequence()constructorfirst new Sequence()instance blocksecond new Sequence()constructorsecond new Sequence()
Read the printed output as a timeline. The static block fires when the class loads and never again; every new repeats the instance block then the constructor body.
NORMAL ~/memra/learn/java-from-zero/initialization-order utf-8 LF