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
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"); }}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
Boardstays untouched. Step 2 readsmaxMarksthroughSupplementary, butmaxMarksis declared inExam, so onlyExamis initialized. - Step 3 initializes
FinalExam; its superclassExamis already done. Step 4 runs only the constructor. Step 5 loadsSupplementarywithout initializing it, soSupplementary initializednever prints.
- The main class is initialized before
mainruns. 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.classandforName(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
# app/ has FeeApp.class, lib/fee-calc.jar has FeeCalculator.classjava -cp lib FeeAppjava -cp app FeeAppjava -cp "app;lib/*" FeeAppError: 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
FeeAppand runs it until line 4 needsFeeCalculator. 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 forx.Yby name; fix the name or add its JAR.NoClassDefFoundError: x/YwithCaused by: ClassNotFoundException: compiled code needsY, but its JAR or folder is missing at run time.NoClassDefFoundError: Could not initialize class Y:Ywas found, but its static code failed earlier; find the firstExceptionInInitializerError.
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
# 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:"[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.
Boardnever appears: javac copiedCBSEintomain, so the class is not even loaded.Supplementaryis loaded at step 2 (the field was named through it) but never initialized. - The
LambdaForm$MHlines 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
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)); }}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 ownHostel(app). The chain loop walksgetParent()untilnull. customwas asked forHostel, but delegation passed the request up andappdefined it. SogetClassLoader()saysapp, and the class is the very sameHostel.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