Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Java
Stage 5: Specialization

Part 01 / Topic 6 of 7

The classpath, and reading a classpath error

The classpath is the list of folders (and .jar files, Part 15) where java looks for .class files. By default, it is just the current folder (.) — which is why java Hello works when you are standing in the same folder as Hello.class.

You can see it for yourself: System.getProperty("java.class.path") returns the classpath the JVM is actually using.

public class ClasspathCheck {
    public static void main(String[] args) {
        System.out.println("java.class.path = " + System.getProperty("java.class.path"));
    }
}
$ javac ClasspathCheck.java
$ java ClasspathCheck
java.class.path = .
$ java -cp . ClasspathCheck
java.class.path = .

Both runs print the same thing: with no -cp flag, Java quietly uses -cp . (the current folder) for you.

Real-world example: you cd out of the folder with your .class file, or point -cp somewhere empty, and java can no longer find your class:

$ cd ..
$ java Hello
Error: Could not find or load main class Hello
Caused by: java.lang.ClassNotFoundException: Hello

$ java -cp /tmp/does-not-exist Hello
Error: Could not find or load main class Hello
Caused by: java.lang.ClassNotFoundException: Hello

Both commands fail with the exact same message, for the same reason: java looked in the folder(s) on the classpath, found no Hello.class there, and gave up. ClassNotFoundException means "I searched the classpath and this class was not in it" — it does not mean the file does not exist anywhere, only that it is not where java was told to look.

The fix is always one of two things: cd into the folder that actually has the .class file, or point -cp (or --class-path) at that folder directly:

$ java -cp examples Hello
Hello, World!
Welcome to Java Step by Step

Full program: examples/ClasspathCheck.java.

Done here? The practice set for Part 1 — including the solutions — is on the part page.

Search the guide