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?

3
  • 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. Nov 9, 2011 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, 2016 at 9:23
  • I would suggest looking into gradle. Nov 23, 2020 at 4:49

1 Answer 1

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
3
  • 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.
    – user33076
    Nov 11, 2011 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, 2011 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, 2012 at 7:51

You must log in to answer this question.