Java - Could not find the main class

When I try to run a simple Hello World program I keep getting a message saying Could not find the main class.

I found this thread on Ubuntu Forums which suggested that my CLASSPATH variable is messed up, but I couldn't find a way to fix it.

What am I doing wrong?


Solution 1:

When the code looks like:

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

you need to run java Foo in the directory containing Foo.class (after compiling with javac Foo.java). If you're in a different directory, say ~ where the class file is located at ~/bar/Foo.class, you need to set the classpath before running java:

CLASSPATH=~/bar java Foo

If you're using packages, e.g.:

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

then you need to save it to path/bar/Foo.java and compile path/bar/Foo.class with javac path/bar/Foo.java and run from path/:

java bar.Foo