NoClassDefFoundError is an Error ,occurs when the source was successfully compiled but at runtime, the required class files were not found.
It may also arise when the class is already loaded in different classloader(usually a parent classloader would have loaded the class and hence the class cannot be loaded again) or if an incompatible class definition has been found – the name in the class file does not match the requested name.
It is usually thrown on new() statements or method invocations that load a previously absent class when the class loader is unable to find or load the class.
ClassNotFoundException is an Exception , thrown when an application tries to load a class through its string name but no definition for the class with the specified name could be found, say for example if a application uses Class.forName() or ClassLoader.findSystemClass() or ClassLoader.loadClass() passing a class name as String parameter may result in exception if no definition for that class is found or invalid binary name is encountered.
import java.io.Serializable;
// class used for creating sample objects
public class Vehicle implements Serializable{
private static final long serialVersionUID = 12323L;
// Sample class variable
private int wheels;
// default public construtor
public Vehicle(){
// Setting arbitrary value for example purpose
this.wheels = 4;
}
// Accessor methods for the class variable
public int getWheels(){
return this.wheels;
}
public void setWheels(int wheels){
this.wheels = wheels;
}
}
NoClassDefFoundError |
ClassNotFoundException |
public class NoClassDefFoundExample {
public static void main(String[] args) {
// Get a new instance of our sample class
Vehicle v = new Vehicle();
// call the method to check if we got the instance correctly
System.out.println(“Vehicle wheels count :” + v.getWheels());
}
} |
import java.lang.reflect.*;
public class ClassNotFoundExample {
public static void main(String[] args) throws Exception {
// Get a class instance for the sample Vehicle class
// Throws ClassNotFoundException
Class c = Class.forName(“Vehicle”);
// Get a new instance of the above class at runtime
// Throws InstantiationException, IllegalAccessException
Vehicle v = (Vehicle) c.newInstance();
// call the method to check if we got the instance correctly
System.out.println(“Vehicle wheels count : ” + v.getWheels());
}
} |
To understand the difference between the two and usage of the code above, follow these steps :
1. Prepare the source file for above code. There will be three .java files. Compile these java files to get the three corresponding class files :
2. Try to run the two programs (ClassNotFoundExample and NoClassDefFoundExample) in turn. You’ll get the correct result for first time. As shown below :
3. Now simply delete the Vehicle.class file from your folder and without re-compiling the code, try to run the above two programs again. Bingo… you’ve just got the Error and the Exception you’ve been looking for :