# How to Fix Java ClassNotFoundException: Class Not Found Error
You're running your Java application and suddenly hit this error:
Exception in thread "main" java.lang.ClassNotFoundException: com.mysql.cj.jdbc.Driver
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:581)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
at java.base.ClassLoader.loadClass(ClassLoader.java:522)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:315)
at com.myapp.DatabaseManager.connect(DatabaseManager.java:25)
at com.myapp.Main.main(Main.java:12)This error means the JVM cannot locate a class your code is trying to load at runtime. Unlike compile-time errors where the compiler catches missing classes, this happens during execution.
Understanding the Root Cause
The ClassNotFoundException occurs when you try to load a class dynamically using:
Class.forName("com.example.SomeClass")ClassLoader.loadClass("com.example.SomeClass")Class.forName().newInstance()
The class exists in your source code references but isn't available in the runtime classpath.
Diagnosis Steps
Step 1: Identify the Missing Class
Look at the error message right after ClassNotFoundException:. In our example, it's com.mysql.cj.jdbc.Driver. This is the fully qualified class name the JVM cannot find.
Step 2: Check Your Dependencies
Verify the JAR containing the class is available:
```bash # For Maven projects mvn dependency:tree | grep mysql
# For Gradle projects gradle dependencies | grep mysql ```
Step 3: Verify the Classpath
Print your current classpath:
```bash # Running Java directly java -cp "." MyMainClass
# Check what's in your classpath echo $CLASSPATH
# For Maven, see the effective classpath mvn dependency:build-classpath -Dmdep.outputFile=classpath.txt cat classpath.txt ```
Step 4: Locate the Missing JAR
Search Maven Central for the correct dependency:
# Search for MySQL connector
curl -s "https://search.maven.org/solrsearch/select?q=g:mysql+AND+a:mysql-connector-java&rows=5&wt=json" | jq '.response.docs'Solutions
Solution 1: Add Missing Dependency (Maven)
Add the MySQL connector to your pom.xml:
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.33</version>
</dependency>Then rebuild:
mvn clean installSolution 2: Add Missing Dependency (Gradle)
Add to your build.gradle:
dependencies {
implementation 'mysql:mysql-connector-java:8.0.33'
}Then rebuild:
gradle clean buildSolution 3: Add JAR to Classpath Manually
If you're running without a build tool:
```bash # Download the JAR first wget https://repo1.maven.org/maven2/mysql/mysql-connector-java/8.0.33/mysql-connector-java-8.0.33.jar
# Run with explicit classpath java -cp ".:mysql-connector-java-8.0.33.jar" com.myapp.Main ```
Solution 4: Fix Wrong Class Name
Sometimes the class name in your code is incorrect or outdated:
```java // Wrong (old driver class) Class.forName("com.mysql.jdbc.Driver");
// Correct (MySQL 8+ driver class) Class.forName("com.mysql.cj.jdbc.Driver"); ```
Solution 5: Fix IDE Configuration
If using an IDE, the dependency might be missing from the deployment assembly:
- 1.For Eclipse:
- 2.Right-click project -> Properties -> Deployment Assembly
- 3.Add -> Java Build Path Entries -> Select your JAR
- 1.For IntelliJ IDEA:
- 2.File -> Project Structure -> Artifacts
- 3.Add your library to the artifact's output directory
Verification
After applying the fix, verify the class is loaded:
public class ClassLoadTest {
public static void main(String[] args) {
try {
Class<?> driverClass = Class.forName("com.mysql.cj.jdbc.Driver");
System.out.println("Class loaded successfully: " + driverClass.getName());
} catch (ClassNotFoundException e) {
System.err.println("Failed to load class: " + e.getMessage());
e.printStackTrace();
}
}
}Run and confirm output:
Class loaded successfully: com.mysql.cj.jdbc.DriverCommon Scenarios
| Scenario | Root Cause | Fix |
|---|---|---|
| JDBC driver not found | Missing connector JAR | Add MySQL/PostgreSQL dependency |
| JSON processing fails | Missing Jackson/Gson | Add JSON library dependency |
| Logging fails | Missing SLF4J implementation | Add logback or log4j2 |
| Class worked in IDE but fails deployed | Build tool not packaging dependency | Check Maven shade/assembly plugin |
Prevention Tips
- 1.Always use a build tool (Maven/Gradle) instead of manual classpath management
- 2.Scope dependencies correctly - use
runtimescope for JDBC drivers - 3.Use dependency management - define versions in a properties section
- 4.Test in clean environments - ensure your build produces a complete artifact
When this error appears, start by identifying the missing class, then trace it back to the dependency that should contain it. Add the missing dependency, rebuild, and the error resolves.