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 MyProgram3. 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.x5. Check module exports (Java 9+)
// If you get ClassNotFoundException with modules, add:
// --add-exports java.base/sun.security.x509=ALL-UNNAMEDBuilt by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro