0
votes

Alright, so I was making a simple Java class that would simply print out "Hello!". Here is the code:

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

I compiled the class through the command prompt and then, when I wanted to run it, it gave me a NoClassDefFoundError suggesting that there is a problem with the classpath. That is really stupid since it is a one-class program. I tried many things but nothing seems to fix the problem.

How can I fix this?

2
What commands did you execute to compile and run?逆さま
@Agadoo: If the answer from Jon helped you to solve the problem, please accept it (using the check mark button beside it). This helps us to know there is nothing more to do.Paŭlo Ebermann

2 Answers

6
votes

You haven't shown how you ran the code. My guess is that you ran:

java Hello.class

which tries to run a class called Hello.class. The class is just named Hello, so you need:

java Hello

If you haven't set a CLASSPATH environment variable, that should be fine. Otherwise, either set it to a path including . or specify it on the command line:

java -cp . Hello

Of course, this is assuming you compiled the code first, using a command like this:

javac Hello.java
0
votes

You have the environment variable CLASSPATH set, but it doesn't include a "." (dot) to represent the current directory (as the default does.) Run like this:

java -cp . Hello

That's "java space dash cp space dot space Hello".

Once you get past "Hello, World", you'll find that setting the class path becomes necessary all the time -- whether by hand like this (rarely, in the real world) or in a startup script, build tool, or IDE.

Use of the CLASSPATH environment variable is a bad practice leftover from Java's early days. Often you'll find that it's Apple's QuickTime installer that is setting it to something. You should never use or rely on this variable.