Skip to content
Fix Code Error

How to solve java.lang.NoClassDefFoundError?

March 13, 2021 by Code Error
Posted By: Anonymous

I’ve tried both the example in Oracle’s Java Tutorials. They both compile fine, but at run-time, both come up with this error:

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

I think I might have the Main.java file in the wrong folder. Here is the directory hierarchy:

graphics
├ Main.java
├ shapes
|   ├ Square.java
|   ├ Triangle.java
├ linepoint
|   ├ Line.java
|   ├ Point.java
├ spaceobjects
|   ├ Cube.java
|   ├ RectPrism.java

And here is Main.java:

import graphics.shapes.*;
import graphics.linepoint.*
import graphics.spaceobjects.*;

public class Main {
    public static void main(String args[]) {
        Square s = new Square(2,3,15);
        Line l = new Line(1,5,2,3);
        Cube c = new Cube(13,32,22);
    }
}

What am I doing wrong here?

UPDATE

After I put put the Main class into the graphics package (I added package graphics; to it), set the classpath to “_test” (folder containing graphics), compiled it, and ran it using java graphics.Main (from the command line), it worked.

Really late UPDATE #2

I wasn’t using Eclipse (just Notepad++ and the JDK), and the above update solved my problem. However, it seems that many of these answers are for Eclipse and IntelliJ, but they have similar concepts.

Solution

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/.

Side note: I would recommend taking advantage of the amazing tooling that exists for Java and JVM languages. Modern IDE’s like Eclipse and IDEA and build management tools like Maven or Gradle will help you not have to worry about classpaths (as much) and focus on the code! That said, this link explains how to set the classpath when you execute on the command line.

Answered By: Anonymous

Related Articles

  • How to limit the number of total animated drop cubes…
  • TLS 1.3 server socket with Java 11 and self-signed…
  • ClassNotFoundException:…
  • Apache server keeps crashing, "caught SIGTERM,…
  • Problems using Maven and SSL behind proxy
  • Maven2: Missing artifact but jars are in place
  • Examples of GoF Design Patterns in Java's core libraries
  • UnsatisfiedDependencyException: Error creating bean…
  • How to disable SSL certificate checking with Spring…
  • Ubuntu apt-get unable to fetch packages
  • Eclipse JUnit - possible causes of seeing…
  • java.lang.NoClassDefFoundError in junit
  • setting JAVA_HOME & CLASSPATH in CentOS 6
  • Android- Error:Execution failed for task…
  • Form field border-radius is not working only on the…
  • Neither BindingResult nor plain target object for…
  • What does 'Unsupported major.minor version 52.0'…
  • "PKIX path building failed" and "unable to find…
  • "Non-resolvable parent POM: Could not transfer…
  • JPA Hibernate Persistence exception…
  • Address already in use: JVM_Bind
  • Unsupported major.minor version 52.0 in my app
  • Eclipse will not start and I haven't changed anything
  • Spring Boot with ElasticSearch in Groovy: WebClient…
  • java.lang.NoClassDefFoundError:…
  • Execution failed for task…
  • java.lang.ClassNotFoundException:…
  • Speed comparison with Project Euler: C vs Python vs…
  • 3D Rotation of a camera using its own, new axes
  • java.lang.NoClassDefFoundError:…
  • Java 6 Unsupported major.minor version 51.0
  • Requested bean is currently in creation: Is there an…
  • Class Not Found Exception when running JUnit test
  • PKIX path building failed in Java application
  • Java.lang.NoClassDefFoundError:…
  • Jetpack Compose and Hilt Conflict
  • How to handle invalid SSL certificates with Apache…
  • Keycloak/Wildfly How to configure all console logs…
  • NoClassDefFoundError on Maven dependency
  • Could not find main class HelloWorld
  • How to initialize an array of objects in Java
  • How Spring Security Filter Chain works
  • Caused By: java.lang.NoClassDefFoundError:…
  • "java.lang.OutOfMemoryError: PermGen space" in Maven build
  • java.lang.ClassNotFoundException:com.mysql.jdbc.Driver
  • How to ignore PKIX path building failed:…
  • NoClassDefFoundError while trying to run my jar with…
  • java IO Exception: Stream Closed
  • What are the best JVM settings for Eclipse?
  • How to cube a squared answer using Java inheritance
  • NullpointerException error while working with…
  • Spring schemaLocation fails when there is no…
  • Non-resolvable parent POM for Could not find…
  • Is gl_FragDepth equal gl_FragCoord.z when msaa enable?
  • java.lang.NoClassDefFoundError:…
  • java.lang.NoClassDefFoundError:…
  • java.lang.UnsupportedClassVersionError Unsupported…
  • ClassNotFoundException com.mysql.jdbc.Driver
  • JUNIT Test class in Eclipse -…
  • When I'm testing a web app by JUnit and Mockito I…
  • Integrate ZXing in Android Studio
  • Eclipse - Run in Debug Mode fails
  • Pentaho Data Integration SQL connection
  • How do I put all required JAR files in a library…
  • java.lang.RuntimeException: Unable to instantiate…
  • Launching Spring application Address already in use
  • Unable to solve java.sql.SQLException even after…
  • Java web start - Unable to load resource
  • Exception in thread "main"…
  • javax.faces.application.ViewExpiredException: View…
  • A fatal error has been detected by the Java Runtime…
  • android studio 0.4.2: Gradle project sync failed error
  • Jetty: HTTP ERROR: 503/ Service Unavailable
  • how to run or install a *.jar file in windows?
  • How can I throw CHECKED exceptions from inside Java…
  • Javascript and css animation
  • Plugin…
  • What causes and what are the differences between…
  • How to execute a java .class from the command line
  • How to run TestNG from command line
  • Multipart File Upload Using Spring Rest Template +…
  • ClassNotFoundException thrown
  • How can I resolve Web Component Testing error?
  • org.glassfish.jersey.servlet.ServletContainer…
  • Execute jar file with multiple classpath libraries…
  • javax.xml.bind.JAXBException: Class *** nor any of…
  • My Application Could not open ServletContext resource
  • Failed to execute goal…
  • For loop in multidimensional javascript array
  • How to affect other elements when one element is hovered
  • Why am I getting a "401 Unauthorized" error in Maven?
  • java.lang.ClassNotFoundException: HttpServletRequest
  • An Authentication object was not found in the…
  • Multithreading: waiting for a thread to finish so I…
  • What's the difference between Instant and LocalDateTime?
  • java.rmi.ConnectException: Connection refused to…
  • How do I run Java .class files?
  • Spring Security exclude url patterns in security…
  • What does "Could not find or load main class" mean?
  • Java program to connect to Sql Server and running…

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

Flexbox: center horizontally and vertically

Next Post:

href=”tel:” and mobile numbers

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

.net ajax android angular arrays aurelia backbone.js bash c++ css dataframe ember-data ember.js excel git html ios java javascript jquery json laravel linux list mysql next.js node.js pandas php polymer polymer-1.0 python python-3.x r reactjs regex sql sql-server string svelte typescript vue-component vue.js vuejs2 vuetify.js

  • you shouldn’t need to use z-index
  • No column in target database, but getting “The schema update is terminating because data loss might occur”
  • Angular – expected call-signature: ‘changePassword’ to have a typedeftslint(typedef)
  • trying to implement NativeAdFactory imports deprecated method by default in flutter java project
  • What should I use to get an attribute out of my foreign table in Laravel?
© 2022 Fix Code Error