Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
java.lang.reflect.Constructor Class in Java
Next article icon

How to Solve java.lang.ClassNotFoundException in Java?

Last Updated : 17 Nov, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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
xml_file

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.

 

output_screen

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

java_build_path

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.

Database Command Line
MySQLmysql-connector-java-8.0.22.jar
MongoDBmongo-java-driver-3.12.7.jar
SQL Serversqljdbc4.jar
MYSQLsqljdbc.jar
Oracleoracle.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. 



Next Article
java.lang.reflect.Constructor Class in Java
author
priyarajtt
Improve
Article Tags :
  • Java
  • Java-Exceptions
Practice Tags :
  • Java

Similar Reads

  • How to Fix java.lang.classcastexception in Java?
    ClassCastException in Java occurs when we try to convert the data type of entry into another. This is related to the type conversion feature and data type conversion is successful only where a class extends a parent class and the child class is cast to its parent class. Here we can consider parent c
    6 min read
  • How to Solve Class Cast Exceptions in Java?
    An unexcepted, unwanted event that disturbed the normal flow of a program is called Exception. Most of the time exceptions are caused by our program and these are recoverable. Example: If our program requirement is to read data from the remote file locating at the U.S.A. At runtime, if the remote fi
    3 min read
  • How to Resolve Java.lang.ExceptionInInitializerError In Java?
    An unexpected, unwanted event that disturbed the normal flow of a program is called an Exception. There are mainly two types of exception in Java: 1. Checked Exception 2. Unchecked Exception ExceptionInInitializerError is the child class of the Error class and hence it is an unchecked exception. Thi
    3 min read
  • ClassNotFoundException Vs NoClassDefFoundError in Java
    Both of the exceptions that are ClassNotFoundException and NoClassDefFoundError occur when the class is not found at runtime. They are related to the Java classpath. ClassNotFoundException ClassNotFoundException occurs when you try to load a class at runtime using Class.forName() or loadClass() meth
    3 min read
  • java.lang.reflect.Constructor Class in Java
    java.lang.reflect.Constructor class is used to manage the constructor metadata like the name of the constructors, parameter types of constructors, and access modifiers of the constructors. We can inspect the constructors of classes and instantiate objects at runtime. The Constructor[] array will hav
    4 min read
  • java.lang.ArrayIndexOutOfBoundsExcepiton in Java with Examples
    The java.lang.ArrayIndexOutOfBoundsException is a runtime exception and thrown only at the execution state of the program. Java compiler never checks for this error during compilation. The java.lang.ArrayIndexOutOfBoundsException is one of the most common exceptions in java. It occurs when the progr
    2 min read
  • Java.lang.Class class in Java | Set 1
    Java provides a class with name Class in java.lang package. Instances of the class Class represent classes and interfaces in a running Java application. The primitive Java types (boolean, byte, char, short, int, long, float, and double), and the keyword void are also represented as Class objects. It
    15+ min read
  • java.lang.reflect.Field Class in Java
    The ability of the software to analyze itself is known as Reflection. This is provided by the java.lang.reflect package and elements in Class .Field serves the same purpose as the whole reflection mechanism, analyze a software component and describe its capabilities dynamically, at run time rather t
    5 min read
  • java.lang.reflect.Method Class in Java
    java.lang.reflect.Method class provides necessary details about one method on a certain category or interface and provides access for the same. The reflected method could also be a category method or an instance method (including an abstract method). This class allows broadening of conversions to oc
    3 min read
  • java.lang.reflect.Proxy Class in Java
    A proxy class is present in java.lang package. A proxy class has certain methods which are used for creating dynamic proxy classes and instances, and all the classes created by those methods act as subclasses for this proxy class. Class declaration: public class Proxy extends Object implements Seria
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences