How can I solve “java.lang.NoClassDefFoundError”

Hello guys, today we will show a common error while working on java based projects. This error is “java.lang.NoClassDefFoundError“. We will see how to solve this.

Exception in thread "main" java.lang.NoClassDefFoundError: graphics/shapes/Square
    at Main.main(Main.java:7)
Caused by: java.lang.ClassNotFoundException: graphics.shapes.Square
    at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    ... 1 more

After you compile your code, you end up with .class files for each class in your program. These binary files are the bytecode that Java interprets to execute your program. The NoClassDefFoundError indicates that the classloader (in this case java.net.URLClassLoader), which is responsible for dynamically loading classes, cannot find the .class file for the class that you’re trying to use.


Your code wouldn’t compile if the required classes weren’t present (unless classes are loaded with reflection), so usually, this exception means that your classpath doesn’t include the required classes. Remember that the classloader (specifically java.net.URLClassLoader) will look for classes in package a.b.c in folder a/b/c/ in each entry in your classpath. NoClassDefFoundError can also indicate that you’re missing a transitive dependency of a .jar file that you’ve compiled against and you’re trying to use.


For example, if you had a class com. example. Foo, after compiling you would have a class file Foo. class. Say for example your working directory is …/project/. That class file must be placed in …/project/com/example, and you would set your classpath to …/project/.

Hope you got the idea, of how to fix it. Thanks.

Leave a Reply