How to Solve java.lang.ClassNotFoundException in Java?
Last Updated :
17 Nov, 2023
In Java, java.lang.ClassNotFoundException is a checked exception and occurs when the Java Virtual Machine (JVM) tries to load a particular class and the specified class cannot be found in the classpath. ClassNotFoundException should be handled with a try-catch block or using the throw keyword.
In older days, there are no editors like Eclipse are available. Even in Notepad, people have done Java coding by using the “javac” command to compile the Java files, and they will create a '.class' file. Sometimes accidentally the generated class files might be lost or set in different locations and hence there are a lot of chances of ClassNotFoundException occurring. After the existence of editors like Eclipse, Netbeans, etc., IDE creates a ClassPath file kind of entry.
Causes of ClassNotFoundException in Java
To load a class, java.lang.ClassNotFoundException uses 3 methods:
- Class.forName(): Used to load the JDBC Driver
- ClassLoader.findSystemClass(): Used to load the class through SystemClass loader.
- ClassLoader.loadClass(): Used to load the class

From the above image, we can see that many jar files are present. They are absolutely necessary if the java code wants to interact with MySQL, MongoDB, etc., kind of databases, and also few functionalities need these jar files to be present in the build path. If they are not added, first editors show the errors themselves and provide the option of corrections too.
ClassNotFoundException in Java Example
Example: Sample program of connecting to MySQL database and get the contents
Java
// Java Program to check for MySQL connectivity Issue
// Importing database (SQL) libraries
import java.sql.*;
// Main Class
public class MySQLConnectivityCheck {
public static void main(String[] args)
{
// Display message for better readability
System.out.println(
"---------------------------------------------");
// Initially setting connection object
// and result set to null
Connection con = null;
ResultSet res = null;
// Try block to check for exceptions
try {
// We need to have mysql-connector-java-8.0.22
// or relevant jars in build path of project
// Loading drivers
// This driver is the latest one
Class.forName("com.mysql.cj.jdbc.Driver");
con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/test?serverTimezone=UTC",
"root", "");
// Try block to check for exceptions
try {
// Set of statements to be checked
}
// Catch block 1
catch (SQLException s) {
// Display message when SQLException is
// encountered
System.out.println(
"SQL statement is not executed!");
}
}
catch (Exception e) {
// In case of general Exception
// print and display the line number where the
// exception occurred
e.printStackTrace();
}
finally {
// Finally for all cases indirectly closing the
// connections & making the resultset and
// connection object to null
res = null;
con = null;
}
}
}
Output
Case 1: In the above code, we are using com.mysql.cj.jdbc.Driver and in that case if we are not having mysql-connector-java-8.0.22.jar, then we will be getting ClassNotFoundException.

Case 2: So, keep the jar in the build path as shown below.

Note: Similarly for any database connectivity, we need to have the respective jars for connecting to that database. The list of database driver jars required by java to overcome ClassNotFoundException is given below in a tabular format
How to Fix java.lang.ClassNotFoundException in Java?
To Resolve ClassNotFoundException in Java, following JAR files are required for respective databases.
|
MySQL | mysql-connector-java-8.0.22.jar |
MongoDB | mongo-java-driver-3.12.7.jar |
SQL Server | sqljdbc4.jar |
MYSQL | sqljdbc.jar |
Oracle | oracle.jdbc.driver.oracledriver |
Note:
- When we are developing Web based applications, the jars must be present in 'WEB-INF/lib directory'.
- In Maven projects, jar dependency should be present in pom.xmlSample snippet of pom.xml for spring boot
Sample snippet of pom.xml for Spring boot
Example - 1: With Spring boot
XML
<!-- Spring boot mongodb dependency -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
Example - 2: Without spring boot
XML
<!-- https://mvnrepository.com/artifact/org.mongodb/mongodb-driver -->
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver</artifactId>
<version>3.6.3</version>
</dependency>
Example - 3: Gradle based dependencies (MongoDB)
XML
dependencies {
compile 'org.mongodb:mongodb-driver:3.2.2'
}
Similarly, other DB drivers can be specified in this way. It depends upon the project nature, the dependencies has to be fixed. For ordinary class level projects, all the classes i.e parent class, child class, etc should be available in the classpath. If there are errors, then also .class file will not be created which leads to ClassNotFoundException, and hence in order to get the whole code working, one should correct the errors first by fixing the dependencies. IDE is much helpful to overcome such sort scenarios such as when the program throws ClassNotFoundException, it will provide suggestions to users about the necessity of inclusion of jar files(which contains necessary functionalities like connecting to database.
Similar Reads
Java Tutorial
Java is a high-level, object-oriented programming language used to build web apps, mobile applications, and enterprise software systems. It is known for its Write Once, Run Anywhere capability, which means code written in Java can run on any device that supports the Java Virtual Machine (JVM).Java s
10 min read
Java OOP(Object Oriented Programming) Concepts
Java Object-Oriented Programming (OOPs) is a fundamental concept in Java that every developer must understand. It allows developers to structure code using classes and objects, making it more modular, reusable, and scalable.The core idea of OOPs is to bind data and the functions that operate on it,
13 min read
Java Interview Questions and Answers
Java is one of the most popular programming languages in the world, known for its versatility, portability, and wide range of applications. Java is the most used language in top companies such as Uber, Airbnb, Google, Netflix, Instagram, Spotify, Amazon, and many more because of its features and per
15+ min read
Non-linear Components
In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Arrays in Java
Arrays in Java are one of the most fundamental data structures that allow us to store multiple values of the same type in a single variable. They are useful for storing and managing collections of data. Arrays in Java are objects, which makes them work differently from arrays in C/C++ in terms of me
15+ min read
Inheritance in Java
Java Inheritance is a fundamental concept in OOP(Object-Oriented Programming). It is the mechanism in Java by which one class is allowed to inherit the features(fields and methods) of another class. In Java, Inheritance means creating new classes based on existing ones. A class that inherits from an
13 min read
Java Exception Handling
Exception handling in Java allows developers to manage runtime errors effectively by using mechanisms like try-catch block, finally block, throwing Exceptions, Custom Exception handling, etc.An Exception is an unwanted or unexpected event that occurs during the execution of a program (i.e., at runti
10 min read
Collections in Java
Any group of individual objects that are represented as a single unit is known as a Java Collection of Objects. In Java, a separate framework named the "Collection Framework" has been defined in JDK 1.2 which holds all the Java Collection Classes and Interface in it. In Java, the Collection interfac
15+ min read
Class Diagram | Unified Modeling Language (UML)
A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Spring Boot Tutorial
Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read