Take the 2-minute tour ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free, no registration required.

When I try to run a simple Hello World program using I keep getting a message saying Could not find the main class. I found this thread: http://ubuntuforums.org/showthread.php?t=1163850 but it was no use. Any ideas? In the thread it says that my CLASSPATH variable is messed up. Does anybody know a fix or a workaround? Thank You.

share|improve this question
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 9 '11 at 18:59

1 Answer 1

up vote 4 down vote accepted

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
share|improve this answer
    
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 '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
    
I suppose yes. Thanks Again. –  user33076 Nov 12 '11 at 14:52
1  
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_n Jan 12 '12 at 7:51

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.