Skip to content
java.lang.ClassNotFoundException

java.lang.ClassNotFoundException

DodaTech 2 min read

ClassNotFoundException is thrown when Class.forName() or dynamic class loading cannot find the requested class on the classpath at runtime.

What It Means

The class you requested is not available to the JVM’s classloader. Unlike NoClassDefFoundError (which means the class was available at compile time), ClassNotFoundException typically occurs during reflective class loading at runtime.

Why It Happens

  • The JAR containing the class is missing from the classpath.
  • You have a typo in the fully-qualified class name.
  • You’re using reflection with Class.forName() and the driver or class isn’t registered.
  • The class exists but isn’t exported from its module (Java 9+ module system).
  • The deployment environment differs from the build environment.

How to Fix It

1. Check the class name spelling

// BUG: typo in class name
Class.forName("com.example.DataBae");  // should be DataBase

// FIX: use the correct fully-qualified name
Class.forName("com.example.Database");

2. Add the missing JAR to your classpath

# Compile with the JAR
javac -cp lib/mysql-connector-java-8.0.33.jar MyProgram.java

# Run with the JAR
java -cp .:lib/mysql-connector-java-8.0.33.jar MyProgram

3. Verify Maven / Gradle dependencies

Maven (pom.xml):

<dependency>
    <groupId>com.mysql</groupId>
    <artifactId>mysql-connector-j</artifactId>
    <version>8.0.33</version>
</dependency>

Gradle (build.gradle):

implementation 'com.mysql:mysql-connector-j:8.0.33'

4. For JDBC drivers, load the correct class

// Correct way to load MySQL driver
Class.forName("com.mysql.cj.jdbc.Driver");  // MySQL 8+

// Old MySQL driver — still used in some legacy code
Class.forName("com.mysql.jdbc.Driver");     // MySQL 5.x

5. Check module exports (Java 9+)

// If you get ClassNotFoundException with modules, add:
// --add-exports java.base/sun.security.x509=ALL-UNNAMED
What's the difference between ClassNotFoundException and NoClassDefFoundError?
ClassNotFoundException is thrown by Class.forName(), loadClass(), and findSystemClass() when the class is not found at runtime. NoClassDefFoundError is thrown when a class was present during compilation but is missing at runtime — a more serious JVM error.
How do I see which JAR files are on my classpath?
Run java -cp or java -verbose:class to print every class the JVM loads. You can also use System.getProperty("java.class.path") in your code to print the classpath string at runtime.
Why does my code compile but throw ClassNotFoundException at runtime?
Compilation only needs the class to compile against (it can be in a JAR). Runtime needs the actual JAR to be on the classpath. The most common cause: you compiled with Maven/Gradle but ran with java -jar without including dependencies.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro