Skip to lesson

Loading, linking and initialization

Before a class can run, the JVM takes it through three phases in a fixed order: loading, linking and initialization. Knowing which phase does what explains many puzzles, such as a static field that reads 0 even though the code says 50.

Loading: reading the bytes and creating the Class object

Loading is the first phase: a class loader finds the class's bytes by name, and the JVM parses them and creates the Class object. On HotSpot (Java 8 and later), the parsed class data is kept in a memory area called metaspace.

The steps a class goes through the first time it is used. 1 Load: read the bytes and build the Class object. 2 Link: verify the bytecode, prepare static fields with default values and resolve names into direct links. 3 Initialize: run static blocks and set static values.

Example 1 · Load now, initialize later

LoadOnlyDemo.javaJava
class ExamFee {    static int fee = 1500;
    static {        System.out.println("  ExamFee initialized");    }
    static int amount() {        return fee;    }}
public class LoadOnlyDemo {    public static void main(String[] args) throws ClassNotFoundException {        ClassLoader loader = LoadOnlyDemo.class.getClassLoader();
        System.out.println("Loading ExamFee without initializing it");        Class<?> c = Class.forName("ExamFee", false, loader);        System.out.println("Loaded: " + c.getName());
        System.out.println("Calling a static method");        System.out.println("Fee: Rs " + ExamFee.amount());    }}
Output
Loading ExamFee without initializing it
Loaded: ExamFee
Calling a static method
  ExamFee initialized
Fee: Rs 1500

What this code does

  • Class.forName("ExamFee", false, loader) loads the class and returns its Class object, but the static block does not run: loading runs no code of the class.
  • The first call to ExamFee.amount() is an active use, so the JVM initializes the class right before the call: the static block prints, then the fee is returned.

Loading runs no code of the class. No static block, no static field assignment. A class can stay loaded for a long time without ever being initialized. Class.forName(name, false, loader) makes this visible: the false means "load it, but do not initialize it".

Linking: verification, preparation and resolution

Linking is the second phase of class loading. The JVM verifies the bytecode, prepares the static fields with default values and resolves symbolic references into direct ones.

Linking joins the loaded class into the running JVM. It has three parts, described below for this small class.

HostelFee.javaJava
public class HostelFee {    static int roomRent = 30000;    static int messFee;    static final int CAUTION_DEPOSIT = 5000;
    static {        messFee = 24000;        System.out.println("HostelFee initialized");    }
    static int total() {        return roomRent + messFee + CAUTION_DEPOSIT;    }}

Example 2 · Symbolic references in the constant pool

Terminal
javac --release 17 HostelFee.javajavap -v HostelFee
Sample output
...
Constant pool:
   #1 = Methodref          #2.#3          // java/lang/Object."<init>":()V
   #2 = Class              #4             // java/lang/Object
...
   #7 = Fieldref           #8.#9          // HostelFee.roomRent:I
   #8 = Class              #10            // HostelFee
...
  #13 = Fieldref           #8.#14         // HostelFee.messFee:I
  #16 = Fieldref           #17.#18        // java/lang/System.out:Ljava/io/PrintStream;
  #17 = Class              #19            // java/lang/System
...
  #24 = Methodref          #25.#26        // java/io/PrintStream.println:(Ljava/lang/String;)V
...

What this code does

  • A real javap -v run on HostelFee.class built by javac 21 with --release 17, trimmed with .... The numbers can differ with another compiler version.
  • The class file names other classes, fields and methods only as text: HostelFee.roomRent:I means "field roomRent of HostelFee, type int". Resolution turns each such entry into a direct reference the first time an instruction uses it.
  • Verification checks that the bytecode is valid and safe: correct types on the operand stack, no jumps into the middle of an instruction, no reading a local variable before it is set.
  • Preparation creates the static fields and sets each one to its default value: 0, false or null. No Java code runs here.
  • Resolution turns symbolic references, such as the text HostelFee.roomRent:I in the class file, into direct references the JVM can use. HotSpot resolves most references lazily, the first time an instruction that uses them runs.

Order of execution

The life of a class, step by step

Tap the steps in the order the JVM does them for a class.

HotSpot verifies classes from your class path. Trusted JDK classes loaded by the bootstrap loader are not verified again by default.

Preparation sets static fields to default values

Preparation gives every static field its default value before any of your code runs: 0 for numbers, false for boolean and null for references. The value written in your source, like = 50, is not there yet.

Example 3 · Reading a static field before its line has run

PreparationDemo.javaJava
class Scholarship {    static int before = peek();    static int seats = 50;    static int after = peek();
    static int peek() {        System.out.println("  peek: seats is " + seats);        return seats;    }}
public class PreparationDemo {    public static void main(String[] args) {        System.out.println("before = " + Scholarship.before);        System.out.println("after = " + Scholarship.after);        System.out.println("seats = " + Scholarship.seats);    }}
Output
  peek: seats is 0
  peek: seats is 50
before = 0
after = 50
seats = 50

What this code does

  • Preparation set seats to 0. Initialization then runs the three lines in order: the first peek() runs before seats = 50, so it sees the default 0.
  • Writing seats directly in before's initializer (static int before = seats;) would not compile: javac reports an illegal forward reference. Calling a method hides the forward read from the compiler, which is how real bugs of this kind slip in.

Normally you never see these defaults, because initialization replaces them before your code reads the field. But code that runs during initialization, such as a static method called from a static field's initializer, can read a field whose own line has not run yet. It then sees the default.

Initialization runs static initializers in source order

Initialization is the last phase: the JVM runs the class's static initializer method, named <clinit> in the class file. javac builds it from every static field assignment and every static block, in the order they appear in the source.

Example 4 · The static initializer that javac builds

Terminal
javap -c -p HostelFee
Sample output
...
  static {};
    Code:
       0: sipush        30000
       3: putstatic     #7                  // Field roomRent:I
       6: sipush        24000
       9: putstatic     #13                 // Field messFee:I
      12: getstatic     #16                 // Field java/lang/System.out:Ljava/io/PrintStream;
      15: ldc           #22                 // String HostelFee initialized
      17: invokevirtual #24                 // Method java/io/PrintStream.println:(Ljava/lang/String;)V
      20: return
}

What this code does

  • javap shows <clinit> as static {}. It stores 30000 into roomRent, then runs the static block: 24000 into messFee and the println. That is exactly the source order.
  • CAUTION_DEPOSIT has no putstatic: its 5000 is a ConstantValue in the class file, and javac also copies 5000 straight into total() as sipush 5000.

Example 5 · Puzzle: a constructor that runs during initialization

SingletonPuzzleDemo.javaJava
class Counter {    static Counter instance = new Counter();    static int a;    static int b = 0;
    Counter() {        a++;        b++;    }}
public class SingletonPuzzleDemo {    public static void main(String[] args) {        System.out.println("a = " + Counter.a);        System.out.println("b = " + Counter.b);    }}
Output
a = 1
b = 0

What this code does

  • Preparation sets instance, a and b to null, 0 and 0. Initialization then runs in source order: first new Counter(), whose constructor makes a and b both 1.
  • Next, static int a; has no value, so nothing happens and a stays 1. Then static int b = 0; runs and resets b to 0. Moving the instance line to the bottom prints a = 1 and b = 1.

The JVM runs <clinit> at most once per class, on first active use (the When a Class Is Initialized lesson lists exactly what counts). If several threads use the class at the same moment, one thread runs it and the others wait until it finishes. A compile-time constant such as static final int CAUTION_DEPOSIT = 5000 is not part of <clinit>. Its value sits in the class file as a ConstantValue attribute, and the JVM sets it itself before any static code runs.

Trace the code

Watch static initialization run top to bottom

public class InitTrace {
static int base = 100;
static int total = bump();
static int bonus = 5;
static int bump() {
System.out.println("bump sees bonus = " + bonus);
return base + bonus;
}
public static void main(String[] args) {
System.out.println("total = " + total);
}
}

Variables

base
100
total
0
bonus
0

Output

(nothing printed yet)

Line 2Preparation already gave every static field its default 0. Initialization now sets base to 100.

Step 1 of 7

VerifyError and what verification protects against

A VerifyError is thrown when a class's bytecode fails the verifier's checks during linking. Bytecode produced by javac in one go is always valid, so a VerifyError usually means the classes do not match each other, or a tool wrote broken bytecode.

Checkout.javaJava
// Payment.javaclass Payment { String describe() { return "generic payment"; } }
// UpiPayment.java, version 1class UpiPayment extends Payment { String describe() { return "UPI payment"; } }
// Checkout.javapublic class Checkout {    public static void main(String[] args) {        Payment p = new UpiPayment();        System.out.println(p.describe());    }}
Output
UPI payment

The classic cause is separate compilation: one class is changed and recompiled, but the classes that use it are not. Bytecode libraries and Java agents that change classes at run time can also produce invalid bytecode.

Example 6 · A real VerifyError from separate compilation

Terminal
javac Payment.java UpiPayment.java Checkout.javajava Checkout# edit UpiPayment.java: remove "extends Payment", then# recompile only that one filejavac UpiPayment.javajava Checkout
Sample output
UPI payment
Error: Unable to initialize main class Checkout
Caused by: java.lang.VerifyError: Bad type on operand stack
Exception Details:
  Location:
    Checkout.main([Ljava/lang/String;)V @12: invokevirtual
  Reason:
    Type 'UpiPayment' (current frame, stack[1]) is not assignable to 'Payment'
...

What this code does

  • A real run on JDK 21, trimmed. Checkout.class was compiled when UpiPayment was a Payment. After only UpiPayment changed, the verifier finds Checkout.main calling a Payment method on something that is no longer a Payment, and refuses the class before any of its code runs.
  • The fix is to recompile everything together (javac *.java, or a clean build in Maven, Gradle or your IDE). javac would then report the real problem as a normal compile error in Checkout.java.
Never switch verification off to hide a VerifyError. The options -Xverify:none and -noverify were deprecated in JDK 13; recompile the classes together instead.

Next step

Check your understanding

12 quick questions