4

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?

Zanna
  • 72,471
  • 1
    Post your code, its the only way. This is a bit out of scope since its not a problem with Ubuntu it self but give it a go. – Bruno Pereira Nov 09 '11 at 18:59
  • @BrunoPereira this is a problem with Ubuntu. Why does it behave differently than MacOSX and Windows? I created a shell script with the gradle application plugin, and my paths are correct. – El Mac Mar 30 '16 at 09:23
  • I would suggest looking into gradle. – Nicholas Saunders Nov 23 '20 at 04:49

1 Answers1

7

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
Lekensteyn
  • 178,864
  • Thanks it Worked! Btw is there any way to make it so that I can run java ~/bar/foo without setting the class path first? Either way thank you very much. –  Nov 11 '11 at 21:14
  • 2
    Does java -cp ~/bar foo count? -cp is the short option for -classpath and is the same as setting CLASSPATH – Lekensteyn Nov 11 '11 at 21:31
  • 2
    Couple comments: first, a strong recommendation to avoid the env var $CLASSPATH like the plague; second, a gentle suggestion to avoid shell-specific expansions, like assuming "~" will evaluate to $HOME. E.g, this works (because "~" expands before Java is run): CLASSPATH=~/tmp java bar.Foo; as does this: java -cp ~/tmp bar.Foo; but this does not (added quotes): java -cp "~/cp" bar.Foo ... but this does work: java -cp "$HOME/bar" ... All these of course have nothing to do with Java, but rather shell quirks, where quotes (or the absence thereof) can cause unexpected results for the uninitiated... – michael Jan 12 '12 at 07:51