ClassNotFoundException versus NoClassDefFoundError
40 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)ClassNotFoundException and NoClassDefFoundError both say "class not found", but they come from different places. The first is your code asking for a class by name; the second is the JVM failing to find a class your compiled code depends on.
ClassNotFoundException: a checked exception from Class.forName or loadClass
ClassNotFoundException is thrown when code asks for a class by a string name at run time, through Class.forName(name) or ClassLoader.loadClass(name), and no loader can find it. It is a checked exception, so the compiler makes you catch it or declare it.
Example 1 · ClassNotFoundException from a name in config
public class DriverCheckDemo { public static void main(String[] args) { String[] names = { "java.time.LocalDate", // in the JDK "com.mysql.cj.jdbc.Driver", // a library that is not on the class path "java.util.Arraylist" // typo: should be ArrayList }; for (String name : names) { try { Class<?> c = Class.forName(name); System.out.println(name + ": found " + c.getSimpleName()); } catch (ClassNotFoundException e) { System.out.println(name + ": ClassNotFoundException: " + e.getMessage()); } } }}java.time.LocalDate: found LocalDate com.mysql.cj.jdbc.Driver: ClassNotFoundException: com.mysql.cj.jdbc.Driver java.util.Arraylist: ClassNotFoundException: java.util.Arraylist
What this code does
- Each name is plain text, so javac compiled every line happily. Only at run time does
Class.forNamefind out that two of the names lead nowhere. - Because the exception is checked, the code is forced to plan for it. The message is just the name that was asked for, which makes typos easy to spot.
The name is only text, so javac cannot check it. Typical causes: a typo in the name, a missing package part, or a library that is not on the class path, such as a database driver whose class name comes from a config file.
NoClassDefFoundError: the class existed at compile time but is missing at run time
NoClassDefFoundError is an Error (a LinkageError) thrown by the JVM itself. Your code used a class directly, with new, a static call or a field, and it compiled because the class existed then.
Example 2 · NoClassDefFoundError: a class file missing at run time
# FeeApp.main calls FeeCalculator.totalFee(85000, 40000)javac FeeApp.java FeeCalculator.javajava FeeApp# now the FeeCalculator class file goes missing (Windows: del)rm FeeCalculator.classjava FeeAppFee app started Total fee: Rs 125000 Fee app started Exception in thread "main" java.lang.NoClassDefFoundError: FeeCalculator at FeeApp.main(FeeApp.java:4) Caused by: java.lang.ClassNotFoundException: FeeCalculator at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:641) at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:188) at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:526) ... 1 more
What this code does
- A real run on JDK 21.
FeeAppstarts and prints its first line, becauseFeeCalculatoris needed only at line 4. Then the JVM's lookup fails and it throwsNoClassDefFoundError. - The
Caused by: ClassNotFoundExceptioncomes from the application loader inside the JVM, not from your code. The line numbers insidejava.basediffer between JDK versions.
Example 3 · The same error inside one program
import java.io.IOException;import java.io.InputStream;
class PickyLoader extends ClassLoader { private final String allowed;
PickyLoader(String allowed) { super("picky", ClassLoader.getPlatformClassLoader()); this.allowed = allowed; }
@Override protected Class<?> findClass(String name) throws ClassNotFoundException { if (!name.equals(allowed)) { throw new ClassNotFoundException(name); // pretend this class file is missing } try (InputStream in = ClassLoader.getSystemResourceAsStream(name + ".class")) { byte[] bytes = in.readAllBytes(); return defineClass(name, bytes, 0, bytes.length); } catch (IOException e) { throw new ClassNotFoundException(name, e); } }}
public class MissingAtRunTimeDemo { public static class Formatter { public static String rupees(int amount) { return "Rs " + amount; } }
public static class Report implements Runnable { public void run() { System.out.println("Report: total fee " + Formatter.rupees(125000)); } }
public static void main(String[] args) throws Exception { new Report().run(); // normal run: both classes found
PickyLoader loader = new PickyLoader("MissingAtRunTimeDemo$Report"); Class<?> c = loader.loadClass("MissingAtRunTimeDemo$Report"); Runnable report = (Runnable) c.getDeclaredConstructor().newInstance(); System.out.println("Report loaded by " + c.getClassLoader().getName()); try { report.run(); } catch (NoClassDefFoundError e) { System.out.println("NoClassDefFoundError: " + e.getMessage()); System.out.println("Caused by: " + e.getCause()); } }}Report: total fee Rs 125000 Report loaded by picky NoClassDefFoundError: MissingAtRunTimeDemo$Formatter Caused by: java.lang.ClassNotFoundException: MissingAtRunTimeDemo$Formatter
What this code does
Reportwas compiled together withFormatter, and the first call works.PickyLoaderthen loads its own copy ofReportbut pretendsFormatter's class file is missing, just like a JAR left off the class path.Reportloads fine; the error appears only whenrun()first needsFormatter. The$names are how nested classes are named in class files.
At run time the JVM tries to load that class on first use and cannot find it.
The stack trace usually ends with Caused by: java.lang.ClassNotFoundException. That inner exception is the JVM's own failed lookup, not a call in your code. Because loading is lazy, the program may run for a while and fail only when it reaches the missing class.
catch (ClassNotFoundException e) around new Helper() does not even compile: javac says the exception is never thrown there. A missing Helper arrives as NoClassDefFoundError.NoClassDefFoundError: Could not initialize class, after a failed static initializer
The same error has a second, very different meaning. NoClassDefFoundError: Could not initialize class X means X.class was found and loaded, but its static initialization threw an exception earlier.
Example 4 · Could not initialize class: a typo in a config value
class UpiLimits { static String configured = "5O00"; // letter O typed instead of zero static int dailyLimitRupees = Integer.parseInt(configured);
static boolean allowed(int amount) { return amount <= dailyLimitRupees; }}
public class CouldNotInitDemo { public static void main(String[] args) { int[] payments = {250, 1200, 90}; for (int amount : payments) { try { System.out.println("Rs " + amount + " allowed: " + UpiLimits.allowed(amount)); } catch (ExceptionInInitializerError e) { System.out.println("Rs " + amount + " -> ExceptionInInitializerError"); System.out.println(" cause: " + e.getCause()); } catch (NoClassDefFoundError e) { System.out.println("Rs " + amount + " -> NoClassDefFoundError: " + e.getMessage()); } } }}Rs 250 -> ExceptionInInitializerError cause: java.lang.NumberFormatException: For input string: "5O00" Rs 1200 -> NoClassDefFoundError: Could not initialize class UpiLimits Rs 90 -> NoClassDefFoundError: Could not initialize class UpiLimits
What this code does
- Only the first payment shows the real cause:
parseIntcannot read5O00. Every later payment getsCould not initialize class UpiLimits, even thoughUpiLimits.classis right there. - In a server log the first error may be hours older than the ones you are looking at. Search the log for the first
ExceptionInInitializerErrorand fix that static code.
The first use threw ExceptionInInitializerError with the real cause. The JVM marked X as failed, and every later use gets this NoClassDefFoundError. So the fix is never the class path here: find the first ExceptionInInitializerError and fix the static code.
Fixing the class path for java -cp and executable JARs
The class path is the list of folders and JARs the application loader searches. Most "not found" problems are a wrong class path. The commands below show the usual forms, and the checks after them catch most mistakes.
# a class in a package: give the folder that holds the "com" folderjava -cp out com.mnx.FeeApp# several entries: ";" on Windows, ":" on macOS and Linuxjava -cp "out;lib/fee-calc.jar" com.mnx.FeeApp# every JAR in a folder (quote it so the shell does not expand *)java -cp "out;lib/*" com.mnx.FeeApp# executable JAR: libraries come from the manifest's Class-Pathjava -jar fee-app.jarExample 5 · java -jar ignores -cp
# fee-app.jar holds FeeApp; lib/fee-calc.jar holds FeeCalculatorjava -jar fee-app.jarjava -cp lib/fee-calc.jar -jar fee-app.jarjava -cp "fee-app.jar;lib/fee-calc.jar" FeeAppjava -cp lib FeeApp# after rebuilding fee-app.jar with "Class-Path: lib/fee-calc.jar" in its manifestjava -jar fee-app.jarFee 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 Exception in thread "main" java.lang.NoClassDefFoundError: FeeCalculator ... Fee app started Total fee: Rs 125000 Error: Could not find or load main class FeeApp Caused by: java.lang.ClassNotFoundException: FeeApp Fee app started Total fee: Rs 125000
What this code does
- A real run on Windows with JDK 21, trimmed. With
-jar, the-cpoption is silently ignored, so adding the library there changes nothing. Running the main class with an explicit class path works. java -cp lib FeeAppfails earlier: the main class itself is not on that class path, so the launcher reportsCould not find or load main class. AClass-Pathline in the JAR's manifest fixesjava -jarfor good.
Example 6 · A small class path checker
import java.io.File;import java.net.URL;
public class ClassPathCheckDemo { static void check(String className) { String file = className.replace('.', '/') + ".class"; URL where = ClassLoader.getSystemResource(file); if (where == null) { System.out.println(className + ": NOT visible - fix the class path"); } else { System.out.println(className + ": found (" + where.getProtocol() + ")"); } }
public static void main(String[] args) { String cp = System.getProperty("java.class.path"); System.out.println("Class path entries: " + cp.split(File.pathSeparator).length); check("ClassPathCheckDemo"); check("java.lang.String"); check("com.mysql.cj.jdbc.Driver"); }}Class path entries: 1 ClassPathCheckDemo: found (file) java.lang.String: found (jrt) com.mysql.cj.jdbc.Driver: NOT visible - fix the class path
What this code does
- Run as
java ClassPathCheckDemofrom its folder, the class path is just.. In an IDE or from a JAR you see more entries andjarinstead offile. ClassLoader.getSystemResourcelooks for the class file without loading the class, so it is a safe way to ask "would this class be found?" before your code needs it.
- The class was compiled, and the
.classor JAR really exists where you think. - For a class in a package, the class path entry is the root folder, and you run the full name
com.mnx.FeeApp. lib/*adds every.jarinlib, but not loose.classfiles or subfolders.java -jarignores-cpand theCLASSPATHvariable. List the libraries in the JAR's manifest asClass-Path: lib/fee-calc.jar(paths relative to the JAR, separated by spaces), or build one JAR that contains everything.
Find the bug
Find the wrong launch command
Each pair compiles into the folder out, then runs. Tap the wrong line, then check the fix.
The class Fees is compiled into out.
Round 1 of 3Next step
Check your understanding
11 quick questions