Wednesday 24 September 2014

Difference Between ClassNotFoundException & NoClassDefFoundError

Assume the following classesprogram
|——–>Test.java
|———>Demo.java
Test.java
———-
public class Test{}
Demo.java
————-
?
1
2
3
4
5
6
7
public class Demo {
          public static void main(String s[])throws Exception {
 
              Class.forName("Test");  //line 1
              Test t=new Test();  //line 2
        }
 }
Observation
ClassNotFoundException
———————————
You keep only line 1(comment line 2),and compile and execute Demo.java,(Donot compile Test.java)it will give you ClassNotFoundException
What ever String you are passing in Class.forName(“—”) is a class name,and it should be there
solution:  Compile both the java files and then execute Demo class
NoClassDefFoundError
————————————–
Keep Only line 2(comment line 1),and compile and Execute Demo.java.The program successfully compiles &     Executes.It is because,when ur class Demo is using class Test,then No need to compile Test.java,when you compile Demo.java,it auto compiles Test.java
So when will I get Error?  Just remove . from ur classpath & recompile
In classpath generally we add  ;.  at last.
This is because,when the JVM looks for the classes,it looks in classpath and when it sees .  , it  understands that it has to look in the current working directory also.
But if you remove . from classpath,then here auto-compilation will not take place,means you have to compile all the classfiles using javac *.java.
Even after you have compiled both the classes,if u try to execute it,it will still show you NoClassDefFoundError,because u have removed . from classpath variable


Now comment both line1 & line 2,and again recompile only Demo.java
Compilation will be successful,but While execution it will give you sameNoClassDefFoundError


Solution:  include ;.  at your classpath

No comments:

Post a Comment