What is the Difference Between NoClassDefFoundError and ClassNotFoundException in Java - onlyxcodes

Friday 17 May 2024

What is the Difference Between NoClassDefFoundError and ClassNotFoundException in Java

Hi, In this tutorial I will explain the difference between NoClassDefFoundError and ClassNotFoundException in Java.


Errors and exceptions are unavoidable issues that developers encounter when working with Java programming. Two common errors among the many exceptions are NoClassDefFoundError and ClassNotFoundException.


Both errors in Java are connected to classpath and Java ClassLoader issues, but they happen in distinct ways and have different names in the language. I'll illustrate the variations between these two errors.


difference between NoClassDefFoundError and ClassNotFoundException in java

What is NoClassDefFoundError?

NoClassDefFoundError is an error that occurs when the Java Virtual Machine (JVM) or a ClassLoader instance tries to load a class that is present at compile-time but is absent at runtime.


Example of NoClassDefFoundError:

In this example, I will show you the NoClassDefFoundError error example. In this example, I will generate two class files and I will delete one class file and show you how JVM throws a NoClassDefFoundError.


class Apple   
{   
    void display()   
    {   
        System.out.println( "apple fruit color is red" );   
    }   
}   
class NoClassDefFoundErrorExample
{   
    public static void main(String args[])    
    {   
        Apple obj = new Apple();   
        obj.display();          
    }   
} 

Output:


apple fruit color is red

Explanation:


In the above Java program I created the Apple named parent class and created NoClassDefFoundErrorExample is the main class in the code above and I have created the void type display() method within the Apple class..


I created an Apple class object and invoked its method in the main method.


In the above program, I mentioned I have generated two .class files upon compilation. The first is Apple.class and the second is NoClassDefFoundErrorExample.class. 


the program mentioned above will generate two .class files upon compilation. Apple.class will be in one, and NoClassDefFoundErrorExample.class in the other

The above program I have compiled and executed successfully.


Now,


The Java Runtime System will throw a NoClassDefFoundError similar to this one if we delete the Apple.class file and execute the NoClassDefFoundErrorExample.class file:


See the screenshot below I deleted Apple.class file.


see the screenshot below we deleted Apple.class file

Output:


After I deleted Apple.class file I again ran the program without compiling after that a NoClassDefFoundError occurred.


H:\Hamid>java NoClassDefFoundErrorExample
Exception in thread "main" java.lang.NoClassDefFoundError: Apple
        at NoClassDefFoundErrorExample.main(NoClassDefFoundErrorExample.java:12)
Caused by: java.lang.ClassNotFoundException: Apple
        at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
        at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:338)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:357)

What is ClassNotFoundException Error?

Java developers are probably familiar with the term ClassNotFoundException. 


The ClassNotFoundException error happens when a class is not found in the classpath when the Java Virtual Machine (JVM) tries to load it at runtime using the Class.forName() or ClassLoader.loadClass() methods. To put it another way, during execution, the JVM is unable to locate the class file.


Example of ClassNotFoundException:

We try to connect to the Oracle database in this Java program using the Java Database Connectivity (JDBC) driver. The driver is loaded using the Class class's forName method. A ClassNotFoundException will be thrown by this program since the driver's JAR file is not present in the classpath.


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

public class ClassNotFoundExceptionExample 
{
    public static void main(String args[]) 
	{
        try 
		{
            Class.forName("oracle.jdbc.driver.OracleDriver");
            Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","tiger");
            System.out.println("database Connect successfully");
        } 
		catch (Exception e) 
		{
            System.out.println("Unable to connect to the database");
            e.printStackTrace();
        }
    }
}

Output:


H:\Hamid>java ClassNotFoundExceptionExample
Unable to connect to the database
java.lang.ClassNotFoundException: oracle.jdbc.driver.OracleDriver
        at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
        at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:338)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
        at java.lang.Class.forName0(Native Method)
        at java.lang.Class.forName(Class.java:264)
        at ClassNotFoundExceptionExample.main(ClassNotFoundExceptionExample.java:10)

The key differences between NoClassDefFoundError and ClassNotFoundException I outlined in the following table:


AttributeNoClassDefFoundErrorClassNotFoundException
TimingRuntimeRuntime
CauseMissing Class at RuntimeClass Not Found
MethodsThrown by the JVMThrown by Class.forName() or ClassLoader.loadClass()

Read Also:

What does double mean in Java

How to Remove a Character from a String in Java

How do you define a method in Java?

What do the replaceAll () do in Java?

Can I use LeetCode for Java?

How to Get the Length of a String in Java

How to make lists of lists in Java?

How to print each word in new line in Java

Why do we use :: (double colon) in Java

How to Replace a Character in a String in Java without using the Replace Method

What are Variable Arguments in Java

Context Switching in Java Thread Example

Java Stream Iterate Example

What Are the 4 types of loops in Java

How to Run Package Program in Java using Command Prompt

What is final class and method in Java

What is Encapsulation in Java with Realtime Example

3 Ways to Create Thread in Java

Java Code to Send Email with Attachment

How to Produce and Consume Restful Webservice in Java

No comments:

Post a Comment

Post Bottom Ad