Search code examples
javaclasspathworking-directory

-cp ./ Why do I always have to manually include the CWD to the CP when running Java?


I never used to have this problem and when I went to run Java programs (in a terminal) I would simply say,

    java className

and the program would run. But lately when I try this I get the error,

could not find or load main class className

To fix this I've been adding -cp ./ my curring working directory to the classpath and then the program runs. I'm not sure what to add to my environment variables so that the current working directory will always be on the class path thus avoiding this longer script,

    java -cp ./ className

According to this StackOverflow post the standard implementation from Oracle looks in the current working directory for the class name first.

(I am using Java 8 and Windows 8.1)


Solution

  • The classpath, if not found on the command line, and not found in the CLASSPATH environment variable, defaults to the current directory.

    -cp classpath

    Specifies a list of directories, JAR files, and ZIP archives to search for class files. Separate class path entries with semicolons (;)

    Specifying -classpath or -cp overrides any setting of the CLASSPATH environment variable.

    If -classpath and -cp are not used and CLASSPATH is not set, then the user class path consists of the current directory (.).

    If you specify -cp, then you must explicitly include . (the current directory) in the classpath, or it will not be included.

    If not using -cp doesn't work, but explicitly stating -cp . does work, then you must have the CLASSPATH environment variable defined, and it must not explicitly include .. That would explain why overriding CLASSPATH by including . with the -cp option works.