Skip to lesson

Class loading practice

A review of this module. Skip it if you feel confident; the next module does not need it.

Fix the mistakes

The slips that cost marks in this module. Spot each one, then check the fix.

Class loading problems, in interviews and in real logs, come down to four skills: predicting when static code runs, reading the error, checking the load log, and knowing which loader is in charge. Each section below is one of them, with a worked program.

Predict static block output and initialization order

Initialization order questions all follow the same short list of rules. Apply them line by line and the output is never a surprise.

Example 1 · Exam season: one program, every initialization rule

ExamSeasonDemo.javaJava
class Log {    static int say(String msg) {        System.out.println("  " + msg);        return 0;    }}
class Board {    static final String NAME = "CBSE";          // compile-time constant    static int b = Log.say("Board initialized");}
class Exam {    static int e = Log.say("Exam initialized");    static int maxMarks = 100;}
class FinalExam extends Exam {    static int f = Log.say("FinalExam initialized");
    FinalExam() {        Log.say("FinalExam object created");    }}
class Supplementary extends Exam {    static int s = Log.say("Supplementary initialized");}
public class ExamSeasonDemo {    static {        Log.say("ExamSeasonDemo initialized");    }
    public static void main(String[] args) throws Exception {        System.out.println("1: board " + Board.NAME);        System.out.println("2: max marks " + Supplementary.maxMarks);        System.out.println("3: new FinalExam()");        new FinalExam();        System.out.println("4: new FinalExam() again");        new FinalExam();        System.out.println("5: forName without init");        Class.forName("Supplementary", false, ExamSeasonDemo.class.getClassLoader());        System.out.println("6: done");    }}
Output
  ExamSeasonDemo initialized
1: board CBSE
  Exam initialized
2: max marks 100
3: new FinalExam()
  FinalExam initialized
  FinalExam object created
4: new FinalExam() again
  FinalExam object created
5: forName without init
6: done

What this code does

  • Step 1 reads a compile-time constant, so Board stays untouched. Step 2 reads maxMarks through Supplementary, but maxMarks is declared in Exam, so only Exam is initialized.
  • Step 3 initializes FinalExam; its superclass Exam is already done. Step 4 runs only the constructor. Step 5 loads Supplementary without initializing it, so Supplementary initialized never prints.
  • The main class is initialized before main runs. Every other class waits for its first active use: new, a static call, or a non-constant static field.
  • Superclasses first, each class once. A static field counts for the class that declares it.
  • Compile-time constants, arrays, X.class and forName(name, false, loader) never initialize.
  • Inside a class, static lines run top to bottom; code running during that can see default values.

Diagnose class path errors from stack traces

Read the first line and the Caused by line of the trace before anything else. Together they tell you which problem you have, as the two traces below show.

Example 2 · Two class path mistakes, two different errors

Terminal
# app/ has FeeApp.class, lib/fee-calc.jar has FeeCalculator.classjava -cp lib FeeAppjava -cp app FeeAppjava -cp "app;lib/*" FeeApp
Sample output
Error: Could not find or load main class FeeApp
Caused by: java.lang.ClassNotFoundException: FeeApp
Fee app started
Exception in thread "main" java.lang.NoClassDefFoundError: FeeCalculator
	at FeeApp.main(FeeApp.java:4)
Caused by: java.lang.ClassNotFoundException: FeeCalculator
...
Fee app started
Total fee: Rs 125000

What this code does

  • A real run on Windows with JDK 21, trimmed (use : instead of ; on macOS). The first command cannot even find the main class, so the launcher stops before any code runs.
  • The second finds FeeApp and runs it until line 4 needs FeeCalculator. The third command has both entries and works.
  • Error: Could not find or load main class X: the main class itself is not on the class path, or you used the wrong package name.
  • ClassNotFoundException: x.Y: code asked for x.Y by name; fix the name or add its JAR.
  • NoClassDefFoundError: x/Y with Caused by: ClassNotFoundException: compiled code needs Y, but its JAR or folder is missing at run time.
  • NoClassDefFoundError: Could not initialize class Y: Y was found, but its static code failed earlier; find the first ExceptionInInitializerError.

Use -verbose:class to answer what was loaded and when

-Xlog:class+load (or -verbose:class) settles any argument about loading, because it shows each class at the moment it is loaded, mixed with your program's output. Filter out JDK classes to see only yours.

Example 3 · The load log of the exam season program

Terminal
# macOS (or Git Bash): hide the JDK's own classesjava -Xlog:class+load ExamSeasonDemo | grep -v -E "source: (shared|jrt)"# Windows Command Prompt: the same filterjava -Xlog:class+load ExamSeasonDemo | findstr /v "shared jrt:"
Sample output
[0.110s][info][class,load] ExamSeasonDemo source: file:/C:/.../season/
[0.114s][info][class,load] Log source: file:/C:/.../season/
[0.126s][info][class,load] java.lang.invoke.LambdaForm$MH/0x000002ee81000400 source: __JVM_LookupDefineClass__
  ExamSeasonDemo initialized
1: board CBSE
[0.130s][info][class,load] Exam source: file:/C:/.../season/
[0.130s][info][class,load] Supplementary source: file:/C:/.../season/
  Exam initialized
...
2: max marks 100
3: new FinalExam()
[0.142s][info][class,load] FinalExam source: file:/C:/.../season/
  FinalExam initialized
  FinalExam object created
4: new FinalExam() again
  FinalExam object created
5: forName without init
6: done

What this code does

  • A real run on JDK 21 with paths shortened. Board never appears: javac copied CBSE into main, so the class is not even loaded. Supplementary is loaded at step 2 (the field was named through it) but never initialized.
  • The LambdaForm$MH lines are small helper classes the JDK generates at run time for string concatenation with +. They are not yours; filter them out too if they get in the way.

Two things often surprise people in this log. A class that is only used through a compile-time constant never appears at all. And a class can appear as loaded without its static block ever running: loading and initialization are separate phases.

Explain loader hierarchy questions

Loader hierarchy questions test three facts. First, the built-in chain: application (app) → platform → bootstrap (null). Second, delegation: a loader asks its parent first, so the class is defined by the highest loader that can find it.

Example 4 · Defining loader versus the loader you asked

LoaderReportDemo.javaJava
import java.sql.Driver;
class Hostel {}
public class LoaderReportDemo {    static String name(ClassLoader l) {        return l == null ? "bootstrap" : l.getName();    }
    public static void main(String[] args) throws Exception {        Class<?>[] classes = {String.class, Driver.class, Hostel.class};        for (Class<?> c : classes) {            System.out.println(c.getSimpleName() + " defined by " + name(c.getClassLoader()));        }
        ClassLoader custom = new ClassLoader("custom", LoaderReportDemo.class.getClassLoader()) {};        StringBuilder chain = new StringBuilder();        for (ClassLoader l = custom; l != null; l = l.getParent()) {            chain.append(l.getName()).append(" -> ");        }        System.out.println("Chain: " + chain + "bootstrap");
        Class<?> viaCustom = custom.loadClass("Hostel");        System.out.println("Asked custom for Hostel, defined by " + name(viaCustom.getClassLoader()));        System.out.println("Same Hostel class: " + (viaCustom == Hostel.class));    }}
Output
String defined by bootstrap
Driver defined by platform
Hostel defined by app
Chain: custom -> app -> platform -> bootstrap
Asked custom for Hostel, defined by app
Same Hostel class: true

What this code does

  • One class from each built-in loader: String (bootstrap), java.sql.Driver (platform on JDK 21) and your own Hostel (app). The chain loop walks getParent() until null.
  • custom was asked for Hostel, but delegation passed the request up and app defined it. So getClassLoader() says app, and the class is the very same Hostel.class.

Third, identity: a class is its name plus its defining loader.

When you are asked "which loader loaded X?", answer with the defining loader: the one that called defineClass, which getClassLoader() returns. The loader you called loadClass on may only have passed the request up.

Finish up

Mark complete & continue

Next: The interpreter and the JIT compiler