views:

89

answers:

3

I created a file called "Hello.java" that looks like this:

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

I ran javac Hello.java, then java Hello, and everything worked as expected.

I then added the line package testpackage; to the top of the file, and put it in the directory /home/matthew/Desktop/hellotest/testpackage. I put .:/home/matthew/Desktop/hellotest in my CLASSPATH, and compiled and ran the same way as before. But now, I get this error:

matthew@matthew-laptop:~/Desktop/hellotest/testpackage$ java Hello 
Exception in thread "main" java.lang.NoClassDefFoundError: Hello (wrong name: testpackage/Hello)
    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)
    at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:334)
Could not find the main class: Hello. Program will exit.

Why did it work on its own, but not in a package?

+8  A: 

Go up one directory, and run:

java testpackage.Hello
Matthew Flaschen
+5  A: 

Now that it's in testpackage, its name is really testpackage.Hello. So go up a directory and do java on that.

Vuntic
+2  A: 

Try java testpackage.Hello.

Because this is in your classpath, you should be able to run that from any working directory, but refer to it by its full name.

mmsmatt