This article represents tips on How to Fix java.lang.NoClassDefFoundError when compiling a particular Java file. Please feel free to comment/suggest if I missed to mention one or more important points. Also, sorry for the typos.

• How to reproduce java.lang.NoClassDefFoundError?
• Why does the java.lang.NoClassDefFoundError occur in the first place?
• How to Fix the Error?
###### How to reproduce java.lang.NoClassDefFoundError?

Take a look at following Class file.

package com.test;

public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello World! How are you?");
}
}


Following are steps to reproduce the java.lang.NoClassDefFoundError.

• Save the above file as HelloWorld.java within any folder.
• Compile the file using javac command using following: “javac HelloWorld.java”
• Start the JVM using command such as “java HelloWorld”.
• Following error would show up:
java.lang.NoClassDefFoundError: HelloWorld (wrong name: com/test/HelloWorld)
at java.net.URLClassLoader.access$100(Unknown Source) at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)


###### Why does the java.lang.NoClassDefFoundError occur in the first place?

Following happens when you start JVM using “java HelloWorld.java”:

• JVM tries to find “HelloWorld” class file within the cache. If found, the class loading is done which is then followed by linking, initialization and method execution.
• If the class is not found in the cache, JVM follows the delegation model to find the class. In this model, the “AppClassLoader” delegates the parent classloader (Extension classloader) to find the class (in ext directory) which then delegates the activity to BootClassLoader to find the class in %JAVA_HOME%/hre/lib/rt.jar.
• If not found, the AppClassLoader tries to find the class in current folder. However, given the package information, “com.test”, the class is expected to find in “com\test” folder.

###### How to fix the java.lang.NoClassDefFoundError?

Take a look at following Class file.

package com.test;

public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello World! How are you?");
}
}


Do following to print “Hello World! How are you?”:

• Create folder com/test
• Place the following file, HelloWorld.java in com/test folder.
• Compile the file from top most folder consisting of com folder using following command: “javac com\test\HelloWorld.java”
• From topmost folder consisting of com folder, execute the following command, “java com.test.HelloWorld”. And, it should be fine.