-1

I'm just trying to compile a simple hello world file via the terminal. Here's the code for Hello.java:

package Hello;
public class Hello {
    public static void main(String[] args) {        
        System.out.println("Hello, world!");
    }
}

this is saved in another folder, so in terminal I typed:

cd code/repositories/java to navigate to the correct directory (where I saved Hello.java) I next typed javac Hello.java and hit return. It compiled without any errors. I then tried to open the file with java Hello and it threw the following exception:

 Exception in thread "main" java.lang.NoClassDefFoundError: Hello (wrong name: Hello/Hello)
   at java.lang.ClassLoader.defineClass1(Native Method)
   at java.lang.ClassLoader.defineClassCond(ClassLoader.java:631)
   at java.lang.ClassLoader.defineClass(ClassLoader.java:615)
   at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:141)
   at java.net.URLClassLoader.defineClass(URLClassLoader.java:283)
   at java.net.URLClassLoader.access$000(URLClassLoader.java:58)
   at java.net.URLClassLoader$1.run(URLClassLoader.java:197)
   at java.security.AccessController.doPrivileged(Native Method)
   at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
   at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
   at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
   at java.lang.ClassLoader.loadClass(ClassLoader.java:247

How/why does this happen and how do I go about fixing it?

royhowie
  • 11,075
  • 14
  • 50
  • 67
  • 1
    You need to run the `java` command from the classpath installation directory (up one level) – Kon Aug 21 '13 at 01:07
  • so I should just `cd ~` first? – royhowie Aug 21 '13 at 01:09
  • I also had a second problem (I had to remove `package hello;`), hence "trying to compile a java program in terminal"—terminal wasn't the only problem. The java part was also wrong, so idk if it's an exact duplicate... – royhowie Aug 21 '13 at 01:46

2 Answers2

6

The package is called Hello which makes the full qualified name Hello.Hello which means you need to have your Hello.java file in code/repositories/java/Hello

then cd to the code/repositories/java folder and call javac javac Hello/Hello.java then you can run it java Hello.Hello

On a different note, Java standard naming conventions recommend package names use lowercase letters so consider changing the package to "hello"

dkatzel
  • 31,188
  • 3
  • 63
  • 67
2

Remove line package Hello;. Compile and run.

Pawel
  • 1,457
  • 1
  • 11
  • 22
  • awesome, it worked! This was originally written in Netbeans, so I understand the difference (it's just a file without said `Hello` container folder). – royhowie Aug 21 '13 at 01:18
  • I had the same problem. I also coppied the code from NetBeans. – Pawel Aug 21 '13 at 01:19