Saturday, 7 September 2019

Difference between NoClassDefFoundError and ClassNotFoundException in Java

        Both NoClassDefFoundError and ClassNotFoundException occurs when particular class is not found at run time.They related to java classpath only but occurs different scenario's.

Difference:-

ClassNotFoundException Vs NoClassDefFoundError
ClassNotFoundException Vs NoClassDefFoundError

1) Java Program to illustrate ClassNotFoundException

    The below code is to throw the ClassNotFoundException because JavaClass class is not found in the classpath.



ClassNotFoundExceptionExample.java

package com.example.demo;

public class ClassNotFoundExceptionExample {
 
         public static void main(String[] args) {
  
                  try {
                       Class.forName("JavaClass");
                  } catch (Exception ex) {
                       ex.printStackTrace();
                  }
         }

}
Output:-
java.lang.ClassNotFoundException: JavaClass
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
at com.example.demo.ClassNotFoundExceptionExample.main(ClassNotFoundExceptionExample.java:8)


2) Program to illustrate NoClassDefFoundError

      For this you don't use any IDE, use command prompt, compile and run separately. In the below code example, created Employee class in the current class. After compilation JVM will create two classes NoClassDefFOundErrorExample.class and Example.class, before run main class delete Example.class and run the main class.

NoClassDefFoundErrorExample.java

package com.example.demo;

public class NoClassDefFOundErrorExample {
 
         public static void main(String[] args) {
                  Example ex = new Example();
                  ex.getNumber();
         }
}

Run this command for compilation,

>javac NoClassDefFoundErrorExample.java

After compilation, delete Example.class file and run the below command,

> java NoClassDefFoundErrorExample

Exception in thread "main" java.lang.NoClassDefFoundError.


Related Posts:-
1) Exception Handling Interview questions and answers
2) String Interview Questions and Answers
3) Java Program to check the given number is a palindrome or not
4) Factory Design Pattern in Java
5) Java 8 features with examples
6) Difference between Loose Coupling and Tight Coupling in Java With Examples.
7) Difference between final,finalize and finally in Java

1 comment: