Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What is ClassNotFoundException in Java?
3.
What Causes ClassNotFoundException in Java?
4.
Example of ClassNotFoundException in Java
4.1.
Java
5.
How to fix the ClassNotFoundException in Java?
6.
Difference between Classpath and ClassNotFoundException
7.
Frequently Asked Questions
7.1.
What is ClassNotFoundException in Java with example?
7.2.
How do ClassNotFoundException and ClassdefNotFound differ from one another?
7.3.
What is the ClassNotFoundException exception?
7.4.
What type of exception is ClassNotFoundException?
8.
Conclusion
Last Updated: Mar 27, 2024
Easy

ClassNotFoundException in Java

Author Shivani Singh
0 upvote
Master Power BI using Netflix Data
Speaker
Ashwin Goyal
Product @
18 Jun, 2024 @ 01:30 PM

Introduction

One of the nightmares that every Java developer encounters daily is the ClassNotFoundException. At first, ClassNotFoundException appears to be very easy to understand. However, its underlying causes can vary. This blog will cover the ClassNotFoundException in Java, the reason behind its occurrence, and possible solutions.

ClassNotFoundException in Java

When the JVM cannot locate a class a Java program refers to, a ClassNotFoundException is raised in Java. The ClassNotFoundException problem can arise for many causes, but it typically indicates that the target class is not on the classpath. Let's dive deep into the blog ClassNotFoundException in Java to learn more about this. 

Also see,  Swap Function in Java

What is ClassNotFoundException in Java?

ClassNotFoundException is a subclass of java.lang.Exception in Java. The classNotFoundException in Java, as its name implies, happens when the JVM (Java Virtual Machine) tries to load a specific class but cannot locate it in the classpath you gave. This indicates a broken classpath, a relatively prevalent issue in the Java community. 

The ClassNotFoundException most frequently arises when an external dependency is unavailable and results from incorrect application settings. For Java newbies, this issue might be very perplexing. 

Another crucial aspect of this exception is that it is a checked exception. If you use methods that may inadvertently raise a ClassNotFoundException in Java, you must explicitly handle the exception using a try-catch block or a throws clause. 

Let us see in detail how the ClassNotFoundException in Java occurs. 

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

What Causes ClassNotFoundException in Java?

Several common causes for a ClassNotFoundException to be issued include:

  • The class is absent from the classpath: This is the most common reason why a ClassNotFoundException occurs. If the class is not on the classpath, the JVM will not be able to locate it.
     
  • Class name not matched: Even if a class is on the classpath, the JVM won't be able to detect it if the name is misspelled.
     
  • The class comes in a separate package: The JVM won't be able to find the class if it is in a separate package from the one you are attempting to import.
     
  • The class is in a JAR file, not on the classpath: If this is the case, the JVM cannot locate the class.
     
  • Version compatibility issues: The JVM won't be able to find the class if it isn't in the Java version you are using.
     
  • This exception may also be generated if a class is loaded from the classpath but is not available at runtime because some dependencies are missing or if the version of the loaded class and the class at runtime differ.
     
  • When the findSystemClass() method is used by the classloader to attempt to load a class.
     
  • When utilizing Java's ClassLoader loadClass() function.

Example of ClassNotFoundException in Java

The most common example of the ClassNotFoundException in Java is the following:

  • Java

Java

import java.sql.Connection;
import java.sql.DriverManager;

public class Main {
public static void main(String[] args) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "root", "password");
System.out.println("Connection successful to the database");
} catch (ClassNotFoundException e) {
System.out.println("Error: JDBC driver not found!");
e.printStackTrace();
} catch (Exception e) {
System.out.println("Error: Not able to connect to the database!");
e.printStackTrace();
}
}
}

 

Output

Example of ClassNotFoundException in Java

 

Explanation

In the above example, the program uses the Class.forName() function to attempt to load the JDBC driver for MySQL. The class of the driver is com.mysql.jdbc.Driver. 

A ClassNotFoundException will be issued if this class is not in the classpath. The most frequent reason for this exception is this. It occurs when you try to load the JDBC driver while writing the JDBC connectivity code. 

The classpath is missing the MySQL driver jar file in this specific instance of the ClassNotFoundException. 

 

Here, you will see that we utilize the Class.forName ("driver") method to load the driver class contained in a certain jar, in this example, mysql-connector.jar. If the jar is not on the classpath or unavailable to the JVM, it will throw java. lang.ClassNotFoundException: com.mysql.jdbc.Driver.

How to fix the ClassNotFoundException in Java?

The few things which should be followed to fix the ClassNotFoundException in Java are the following:

 

  • Thoroughly go over java.lang.ClassNotFoundException stack trace to identify the Java class that was improperly loaded at runtime.
     
  • Check if the desired class's name is accurate and if the .jar file's location in your classpath is supplied. If not, you require to add it to the classpath of your application manually.
     
  • If it's included in your classpath, there's a reasonable probability that your classpath is overridden or that your application utilizes the classpath supplied in a jar file or start-up script. To resolve this, you need to identify the precise classpath used by your application.
     
  • If a third-party class is to blame for the issue, you must first identify it and add the missing.jar files to your classpath.

 

Now let us see examine frequently asked questions of ClassNotFoundException in Java.

Difference between Classpath and ClassNotFoundException

Basis of Comparison Classpath ClassNotFoundException
Definition  A classpath is a list of locations where all the classes are loaded.  ClassNotFoundException is a subclass of java.lang.Exception in Java. The classNotFoundException in Java, as its name implies, happens when the JVM (Java Virtual Machine) tries to load a specific class but cannot locate it in the classpath you gave.
Purpose  Classpath is set in the program so that it can provide the runtime environment with all the classes and third-party libraries attached to it.  A ClassNotFoundException indicates that the Java Virtual Machine searched the entire classpath you gave but could not locate the class you were trying to reference. Checking your classpath thoroughly is the only workable option.
Use-Case scenario  Classpath needs to be set up by the developers so that JVM has all the necessary JAR files and classes during the runtime of the program The ClassNotFoundException most frequently arises when an external dependency is unavailable and results from incorrect application settings. 

Frequently Asked Questions

What is ClassNotFoundException in Java with example?

The ClassNotFoundException in Java is thrown when the Java Virtual Machine (JVM) searches the full classpath but cannot locate the object. The ClassNotFoundException usually arises at runtime because the class is indirectly loaded via Classloader.

How do ClassNotFoundException and ClassdefNotFound differ from one another?

When looking for a class that isn't on the classpath or when looking up a class that isn't on the runtime classpath using an invalid name, a ClassNotFoundException is raised. A NoClassDefFoundError is raised when a compiled class refers to a different class that isn't on the runtime classpath.

What is the ClassNotFoundException exception?

A classNotFoundException is an exception when looking for a class that isn't on the classpath or when looking up a class that isn't on the runtime classpath using an invalid name, this exception is found. 

What type of exception is ClassNotFoundException?

ClassNotFoundException is a checked exception in Java. This exception is explicitly handled from the code. This is the runtime exception when the JVM cannot locate the class in the classpath. 

Conclusion

As we have reached the end of this blog, let us see what we have discussed so far. In this blog, we have discussed ClassNotFoundException in Java, when it occurs, its example, and how to fix the ClassNotFoundException in Java. 

If you like to learn more, you can check out our articles: 

You may refer to our Guided Path on Code Studios for enhancing your skill set on DSACompetitive ProgrammingSystem Design, etc. Check out essential interview questions, practice our available mock tests, look at the interview bundle for interview preparations, and so much more!

Happy Learning, Ninja!

Live masterclass