Skip to lesson

When a class is initialized

A class can be loaded long before its static code runs. Its static blocks run only at the first active use, and the Java rules say exactly which actions count as one.

Triggers: new, static method call, non-constant static field, Class.forName, reflection

An active use is an action that makes the JVM initialize a class: new, a static method call, a non-constant static field, Class.forName or reflection.

A class is initialized right before its first active use: an action that needs the class's static state to be ready. The JVM runs the static initializer once, and never again for that class.

Example 1 · Five triggers, each one firing once

TriggersDemo.javaJava
import java.lang.reflect.Method;
class Admission {    static { System.out.println("  [Admission initialized]"); }}
class FeeTable {    static { System.out.println("  [FeeTable initialized]"); }
    static int tuition() {        return 85000;    }}
class Hostel {    static int roomsLeft = 42;    static { System.out.println("  [Hostel initialized]"); }}
class Library {    static { System.out.println("  [Library initialized]"); }}
class Shop {    static { System.out.println("  [Shop initialized]"); }
    static String special() {        return "Backpack";    }}
public class TriggersDemo {    public static void main(String[] args) throws Exception {        System.out.println("1. new");        new Admission();
        System.out.println("2. static method call");        System.out.println("  tuition = " + FeeTable.tuition());
        System.out.println("3. read a non-constant static field");        System.out.println("  rooms left = " + Hostel.roomsLeft);
        System.out.println("4. Class.forName with one argument");        Class.forName("Library");
        System.out.println("5. reflection: invoke a static method");        ClassLoader loader = TriggersDemo.class.getClassLoader();        Method m = Class.forName("Shop", false, loader).getDeclaredMethod("special");        System.out.println("  got the Method object");        System.out.println("  special = " + m.invoke(null));
        System.out.println("6. second use: nothing new");        new Admission();        System.out.println("  tuition = " + FeeTable.tuition());    }}
Output
1. new
  [Admission initialized]
2. static method call
  [FeeTable initialized]
  tuition = 85000
3. read a non-constant static field
  [Hostel initialized]
  rooms left = 42
4. Class.forName with one argument
  [Library initialized]
5. reflection: invoke a static method
  got the Method object
  [Shop initialized]
  special = Backpack
6. second use: nothing new
  tuition = 85000

What this code does

  • Each class's static block runs right before its first active use. In step 2 and 3 the block prints before the value line, because the call or field read happens while the string is being built.
  • In step 5, loading Shop with false and getting the Method object did not initialize it; invoke did. Step 6 prints no static block lines: each class is initialized once.
  • Creating an object with new.
  • Calling a static method, or reading or writing a static field that is not a compile-time constant.
  • Class.forName("Name") with one argument (it initializes by default).
  • Reflection that uses the class, such as Method.invoke on a static method or creating an object through a constructor; just getting a Method object does not count.

Predict the output

Does this line start the class?

Read each program and pick what it prints.

Round 1 of 4

A constant is read from Fees.

class Fees {
static final int TUITION = 45000;
static { System.out.print("Fees loaded "); }
}
public class Round1 {
public static void main(String[] args) {
System.out.println(Fees.TUITION);
}
}
Two more triggers: initializing a subclass first initializes its superclass, and the main class is initialized before main runs.

Superclass initialized before subclass, interfaces only when needed

Before a class is initialized, its superclass is initialized, and its superclass before that, up to Object. So new Topper() runs the static code of Person, then Student, then Topper.

Example 2 · Superclass first, and the class that declares the field

SuperFirstDemo.javaJava
class Log {    static int say(String msg) {        System.out.println("  " + msg);        return 0;    }}
class Person {    static int p = Log.say("Person initialized");}
class Student extends Person {    static int s = Log.say("Student initialized");}
class Topper extends Student {    static int t = Log.say("Topper initialized");}
class Vehicle {    static int wheels = 4;    static int v = Log.say("Vehicle initialized");}
class Bus extends Vehicle {    static int b = Log.say("Bus initialized");}
public class SuperFirstDemo {    public static void main(String[] args) {        System.out.println("new Topper():");        new Topper();        System.out.println("new Topper() again:");        new Topper();        System.out.println("Bus.wheels (declared in Vehicle):");        System.out.println("  wheels = " + Bus.wheels);    }}
Output
new Topper():
  Person initialized
  Student initialized
  Topper initialized
new Topper() again:
Bus.wheels (declared in Vehicle):
  Vehicle initialized
  wheels = 4

What this code does

  • new Topper() initializes the whole chain from the top: Person, then Student, then Topper. The second new Topper() prints nothing, because all three are already initialized.
  • Bus.wheels is written through Bus, but wheels is declared in Vehicle, so only Vehicle is initialized. Bus initialized never prints.

Example 3 · When interfaces are initialized

InterfaceInitDemo.javaJava
class Log {    static int say(String msg) {        System.out.println("  " + msg);        return 0;    }}
interface Payable {    int CODE = Log.say("Payable initialized");   // not a constant: needs a method call    int amount();}
interface Discountable {    int RATE = Log.say("Discountable initialized");    default int discount() {        return 10;    }}
class FeeBill implements Payable, Discountable {    static { Log.say("FeeBill initialized"); }
    public int amount() {        return 1200;    }}
public class InterfaceInitDemo {    public static void main(String[] args) {        System.out.println("new FeeBill():");        FeeBill bill = new FeeBill();        System.out.println("amount = " + bill.amount() + ", discount = " + bill.discount() + "%");        System.out.println("read Payable.CODE:");        System.out.println("  CODE = " + Payable.CODE);    }}
Output
new FeeBill():
  Discountable initialized
  FeeBill initialized
amount = 1200, discount = 10%
read Payable.CODE:
  Payable initialized
  CODE = 0

What this code does

  • Initializing FeeBill also initializes Discountable, because it declares a default method, and does it before FeeBill's own static block. Payable has only an abstract method, so it is skipped.
  • Payable is initialized only when its own non-constant field CODE is read. Interface fields are always public static final; CODE is not a compile-time constant because its value comes from a method call.

A static field belongs to the class that declares it. Reading Bus.wheels, where wheels is declared in Vehicle, initializes only Vehicle. Bus is loaded but not initialized. Interfaces are lazier. Initializing a class does not initialize the interfaces it implements, unless an interface declares a default method. Otherwise an interface is initialized only when one of its own non-constant fields is read.

Non-triggers: compile-time constants, array creation, .class literals

Some uses look like active uses but are not. They never run the static code, as the example below shows.

Example 4 · Things that do not initialize a class

NonTriggersDemo.javaJava
class Exam {    static final int MAX_MARKS = 100;        // compile-time constant    static final String BOARD = "CBSE";      // compile-time constant    static final Integer PASS_MARKS = 33;    // not a constant: boxed type    static { System.out.println("  [Exam initialized]"); }}
class Seat {    static { System.out.println("  [Seat initialized]"); }}
public class NonTriggersDemo {    public static void main(String[] args) throws Exception {        System.out.println("MAX_MARKS = " + Exam.MAX_MARKS);        System.out.println("BOARD = " + Exam.BOARD);
        Seat[] hall = new Seat[120];        System.out.println("array of " + hall.length + " seats made");
        Class<?> c = Seat.class;        System.out.println("got " + c.getName() + ".class");
        Class.forName("Seat", false, NonTriggersDemo.class.getClassLoader());        System.out.println("forName(..., false, ...) done");
        System.out.println("Now PASS_MARKS:");        System.out.println("PASS_MARKS = " + Exam.PASS_MARKS);    }}
Output
MAX_MARKS = 100
BOARD = CBSE
array of 120 seats made
got Seat.class
forName(..., false, ...) done
Now PASS_MARKS:
  [Exam initialized]
PASS_MARKS = 33

What this code does

  • MAX_MARKS and BOARD are compile-time constants: javac wrote 100 and CBSE straight into main, so Exam is not initialized. The array, the class literal and forName with false never run Seat's static block either.
  • PASS_MARKS is an Integer, which is not a primitive or String, so it is an ordinary static field. Reading it is an active use, and Exam is finally initialized.
  • Reading a compile-time constant: a static final field of a primitive type or String, set to a constant expression such as 100 or "CBSE". javac copies the value into your code, so the class is not even needed at run time.
  • Creating an array: new Seat[120] makes an array object, not Seat objects.
  • A class literal such as Seat.class, and Class.forName(name, false, loader).
static final Integer PASS = 33; or static final int MAX = compute(); are not compile-time constants. Reading them initializes the class.

Static initialization order and ExceptionInInitializerError

Inside one class, static field initializers and static blocks run top to bottom, after the superclass is done. If any of them throws an unchecked exception, the JVM wraps it in an ExceptionInInitializerError and throws that at the first active use.

Example 5 · A failed static initializer breaks the class for good

InitFailureDemo.javaJava
import java.util.Map;
class ExamConfig {    static Map<String, Integer> passMarks = Map.of("Maths", 35, "Physics", 33);    static int chemistryPass = passMarks.get("Chemistry");   // null -> unboxing fails
    static int pass(String subject) {        return passMarks.get(subject);    }}
public class InitFailureDemo {    public static void main(String[] args) {        try {            System.out.println(ExamConfig.pass("Maths"));        } catch (ExceptionInInitializerError e) {            System.out.println("First use:  " + e.getClass().getSimpleName());            System.out.println("  cause:    " + e.getCause().getClass().getSimpleName());        }
        try {            System.out.println(ExamConfig.pass("Maths"));        } catch (NoClassDefFoundError e) {            System.out.println("Second use: " + e.getClass().getSimpleName());            System.out.println("  message:  " + e.getMessage());        }    }}
Output
First use:  ExceptionInInitializerError
  cause:    NullPointerException
Second use: NoClassDefFoundError
  message:  Could not initialize class ExamConfig

What this code does

  • passMarks.get("Chemistry") returns null, and turning null into an int throws NullPointerException. The JVM wraps it in ExceptionInInitializerError and throws that from the first call to pass.
  • The JVM never retries. The second call fails at once with NoClassDefFoundError: Could not initialize class ExamConfig, although pass("Maths") itself would have worked. On newer JDKs such as 21, its stack trace also names the original error as the cause.

The class is then marked as failed for good. Every later use throws NoClassDefFoundError: Could not initialize class X, even though the class file is right there. The first error in the log holds the real cause; the later ones only repeat that the class is broken. A static block cannot throw a checked exception such as IOException: javac rejects it. Catch it inside the block, or wrap it in an unchecked exception.

Next step

Check your understanding

11 quick questions