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.
<!-- Add missing dependency to pom.xml (Maven) -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.33</version>
</dependency>
// 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
// 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
# 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
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
}
ClassNotFoundException is a checked exception thrown when loading a class dynamically at runtime. NoClassDefFoundError is an error thrown when a class was available at compile time but not at runtime.
Use -cp flag: java -cp .:lib/myjar.jar Main. In Maven, add a dependency in pom.xml. In Gradle, add to dependencies block. In IDEs, right-click project → Add to Build Path.
The MySQL JDBC driver JAR must be in the classpath. Also, MySQL 8+ changed the driver class from com.mysql.jdbc.Driver to com.mysql.cj.jdbc.Driver.
Print System.getProperty("java.class.path") in your code. Use mvn dependency:tree for Maven projects. Use gradle dependencies for Gradle projects.
Yes, it's a checked exception so you must either catch it or declare it with throws. Always handle it gracefully with a meaningful error message.
Explore 500+ free tutorials across 20+ languages and frameworks.