You can load the classes in two ways one is static loading and second way is to dynamically loading the class.
- Static loading - load a class statically using the new operator.
- Dynamic loading - programmatically loading the class using the class loader functions at run time.Using Ex Class.forName/ClassLoader.findSystemClass/ClassLoader.loadClass
You can get NoClassDefFoundError for the following reason
1) You have not set the class path, so the class loader cannot find the .class file ( TestClass)2) You have set the class path, but the class path does not contain the .class file/jar does not contain the specified .class (the call to the new operator fails)
3) It could also happen if the class fails to load as the static initializer block fails for some reason.
You can get ClassNotFoundException if
1) You have set the class path, but the class path does not contain the .class file/jar does not contain the specified .class , so the dynamic loading call class.forName fails.
Use the below example of a class that tries to refer to another TestClass
public class ClassLoaderExceptionTest
public static void main(String args) throws Exception
//Try1Class class = Class.forName("TestClass"); //dynamically loading the class
//Throws ClassNotFoundException if TestClass is missing or removed after compilation/ not present in //class path
TestClass testClass = new TestClass(); // static loading//Throws NoClassDefFoundError if TestClass is missing or removed after compilation/ not present in class //path