Loading, linking and initialization
40 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)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.
Example 1 · Load now, initialize later
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()); }}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 itsClassobject, 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.
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
javac --release 17 HostelFee.javajavap -v HostelFee... 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 -vrun onHostelFee.classbuilt 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:Imeans "fieldroomRentofHostelFee, typeint". 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,falseornull. No Java code runs here. - Resolution turns symbolic references, such as the text
HostelFee.roomRent:Iin 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.
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
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); }}peek: seats is 0 peek: seats is 50 before = 0 after = 50 seats = 50
What this code does
- Preparation set
seatsto0. Initialization then runs the three lines in order: the firstpeek()runs beforeseats = 50, so it sees the default0. - Writing
seatsdirectly inbefore'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
javap -c -p HostelFee...
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
javapshows<clinit>asstatic {}. It stores30000intoroomRent, then runs thestaticblock:24000intomessFeeand theprintln. That is exactly the source order.CAUTION_DEPOSIThas noputstatic: its5000is aConstantValuein the class file, andjavacalso copies5000straight intototal()assipush 5000.
Example 5 · Puzzle: a constructor that runs during initialization
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); }}a = 1 b = 0
What this code does
- Preparation sets
instance,aandbtonull,0and0. Initialization then runs in source order: firstnew Counter(), whose constructor makesaandbboth1. - Next,
static int a;has no value, so nothing happens andastays1. Thenstatic int b = 0;runs and resetsbto0. Moving theinstanceline to the bottom printsa = 1andb = 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
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.
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.
// 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()); }}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
javac Payment.java UpiPayment.java Checkout.javajava Checkout# edit UpiPayment.java: remove "extends Payment", then# recompile only that one filejavac UpiPayment.javajava CheckoutUPI 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.classwas compiled whenUpiPaymentwas aPayment. After onlyUpiPaymentchanged, the verifier findsCheckout.maincalling aPaymentmethod on something that is no longer aPayment, 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 inCheckout.java.
-Xverify:none and -noverify were deprecated in JDK 13; recompile the classes together instead.Next step
Check your understanding
12 quick questions