When i was googling about this I found that information in some of blogs were misleading. Hence an attempt to clear this confusion.
ClassNotFoundException
Java Specification for
ClassNotFoundException
Java Specification for
ClassNotFoundException says below: Thrown when an application tries to load in a class through its string name using:but no definition for the class with the specified name could be found.
- The
forName()method in classClass.- The
findSystemClass method()in classClassLoader.- The
loadClass()method in classClassLoader.
So a
NoClassDefFoundError
Java Specification for
ClassNotFoundException is thrown if an explicit attempt to load a class fails. ClassNotFoundException is thrown because the test attempts the load using an explicit call to loadClass().NoClassDefFoundError
Java Specification for
NoClassDefFoundError says: Thrown if the Java virtual machine or aClassLoaderinstance tries to load in the definition of a class (as part of a normal method call or as part of creating a new instance using the new expression) and no definition of the class could be found.
The searched-for class definition existed when the currently executing class was compiled, but the definition can no longer be found.
Essentially, this means that a
NoClassDefFoundError is thrown as a result of a unsuccessful implicit class load.public class MyNoClassDefFoundTest {
public static void main(String[] args) {
X x = new X();
}
}public class X extends Y {
public void myShow(){
System.out.println("In X");
}
}
public class Y {
public void myShow(){
System.out.println("In Y");
}
Once you have compiled the code, remove the classfile of Y and execute the code. We got to see that it throws NoClassDefFound Error.
Please note that the same error would still occur if X referenced Y
in any other way -- as a method parameter, for example, or as an instance field