Alessandro Power Alessandro Power - 14 days ago 10
Java Question

classpath does not default to current directory

I wrote and compiled a simple Hello World program in Java but when I tried to run it I was greeted with the error message

Error: Could not find or load main class Hello
. It was only after I executed the command
java -cp . Hello
that it successfully ran.

Oddly enough, the current directory already seems to be part of the classpath. The script

class CheckClassPath{
public static void main(String args[]){
System.out.println(System.getProperty("java.class.path"));
}
}


prints
.
, though I again have to explicitly set the
classpath
option.

Does anyone have an idea why this is happening? I am using Ubuntu 16.04 and open-JDK version 1.8.

Answer

I expect that a CLASSPATH environment variable has been set. Run echo $CLASSPATH to see what it is set to.

If you don't use the -jar option then:

  • If there is a -cp, that specifies the classpath
  • Else if CLASSPATH is set in the environment, that specifies the classpath
  • Else a default classpath of "." is used.