Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why am I getting a NoClassDefFoundError when I run a Java class file from the command line in Linux?

I am trying to run a test.class file from the linux command line. I compiled the file using javac test.java which produced the test.class file. When I run the command java test it throws a class not found exception. I also tried specifying the package name with the same result. Here is the output, can anybody help? I believe my syntax is correct according to Google searches.

[root@localhost usr]# java test
Exception in thread "main" java.lang.NoClassDefFoundError: test (wrong name: testJava/test)
        at java.lang.ClassLoader.defineClass1(Native Method)
        at java.lang.ClassLoader.defineClass(ClassLoader.java:634)
        at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
        at java.net.URLClassLoader.defineClass(URLClassLoader.java:277)
        at java.net.URLClassLoader.access$000(URLClassLoader.java:73)
        at java.net.URLClassLoader$1.run(URLClassLoader.java:212)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(URLClassLoader.java:205)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:321)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:294)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:266)
Could not find the main class: test. Program will exit.
like image 426
tier1 Avatar asked Aug 15 '11 18:08

tier1


1 Answers

You need to compile your .java file with javac:

  javac MyFile.java

Then run the file using java

  java MyFile

If you're doing this and it still doesn't work, that means you need to make sure the file and the class name inside the file have the same name... so MyFile.java contains

  class MyFile
  {
     // ...
     public static void main(String[] args)
     {
        // ...
     }
     // ...
  }
like image 55
Patrick87 Avatar answered Oct 07 '22 23:10

Patrick87