ClassNotFoundException in Java — How to Fix (2026) | Tutorials Logic
What is This Error?
The ClassNotFoundException is a checked exception thrown when the JVM tries to load a class at runtime using Class.forName(), ClassLoader.loadClass(), or ClassLoader.findSystemClass(), but cannot find the class definition in the classpath.
Error Message:
java.lang.ClassNotFoundException: com.mysql.jdbc.Driverjava.lang.ClassNotFoundException: org.example.MyClass
Common Causes
Quick Fix (TL;DR)
<!-- Add missing dependency to pom.xml (Maven) -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.33</version>
</dependency>
Common Scenarios & Solutions
Scenario 1: Missing JDBC Driver
// ClassNotFoundException: com.mysql.jdbc.Driver
Class.forName("com.mysql.jdbc.Driver"); // JAR not in classpath!
<!-- Maven pom.xml -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.33</version>
</dependency>
<!-- Also update class name for MySQL 8+ -->
// Old (MySQL 5.x)
Class.forName("com.mysql.jdbc.Driver");
// New (MySQL 8+)
Class.forName("com.mysql.cj.jdbc.Driver"); // Updated class name
Scenario 2: Gradle Dependency Missing
// build.gradle
dependencies {
implementation 'mysql:mysql-connector-java:8.0.33'
implementation 'org.springframework:spring-core:6.0.0'
}
// After adding, run:
// gradle build or ./gradlew build
Scenario 3: Classpath Not Set Correctly
# Compile with classpath
javac -cp .:lib/mysql-connector.jar Main.java
# Run with classpath
java -cp .:lib/mysql-connector.jar Main
# Windows (use ; instead of :)
java -cp .;lib\mysql-connector.jar Main
Scenario 4: Handle Gracefully
try {
Class.forName("com.mysql.cj.jdbc.Driver");
System.out.println("Driver loaded successfully");
} catch (ClassNotFoundException e) {
System.err.println("MySQL driver not found: " + e.getMessage());
System.err.println("Add mysql-connector-java to your classpath");
// Log and handle gracefully
}
Best Practices to Avoid This Error
Related Errors
Key Takeaways
- ClassNotFoundException occurs when JVM cannot find a class in the classpath at runtime
- Most commonly caused by missing JAR files or incorrect dependency configuration
- Use Maven or Gradle to manage dependencies and classpath automatically
- Class names are case-sensitive and must be fully qualified
- Library updates can change class names — check migration guides
- Always catch ClassNotFoundException as it is a checked exception
Frequently Asked Questions
Level Up Your Core java Skills
Master Core java with these hand-picked resources
10,000+ learners
Free forever
Updated 2026
Related Java Topics