Albee
Albee

Reputation: 155

cannot execute a java class java.lang.NoClassDefFoundError:

i'm new to java. i've created a file called HelloWorld.java;

package tp;

 /**
 *
 * @author Utilisateur
 */
    public class HelloWorld {
        public static void main(String[] args) {
            System.out.println("HelloWorld works!");
    }
}

compiled it by executing the command: javac HelloWorld.java in the same folder as HelloWorld.java is in; executed the code by doing: java -cp . HelloWorld in the same folder as HelloWorld.java is in.

but i get this error message

Exception in thread "main" java.lang.NoClassDefFoundError: HelloWorld (wrong nam
e: javaTp/HelloWorld)
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClass(Unknown Source)
    at java.security.SecureClassLoader.defineClass(Unknown Source)
    at java.net.URLClassLoader.defineClass(Unknown Source)
    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)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.launcher.LauncherHelper.checkAndLoadMain(Unknown Source)

can anyone help?

Upvotes: 2

Views: 86

Answers (3)

jacksonps4
jacksonps4

Reputation: 36

The package name is your issue.

Java uses directories in compiled class folders to denote packages. Hence as your HelloWorld class defines itself as being in package 'tp', you need to do one of the following:

You can either run this (with your existing class):

> java -cp . tp.HelloWorld

Or you can remove the package declaration from the top of your class, recompile and run:

> java -cp . HelloWorld

Upvotes: 2

Peter Bratton
Peter Bratton

Reputation: 6408

Because you declared the package tp, Java expects your HelloWorld.class file to live in a directory ./tp.

Typically a Java project will have a nested directory structure compiled to a mirrored one, such as:

src/
  tp/
    HelloWorld.java
classes/
  tp/
    HelloWorld.class

Upvotes: 1

Sujith Surendranathan
Sujith Surendranathan

Reputation: 2579

You need to use the full name: java tp.HelloWorld

Upvotes: 0

Related Questions