Classpath
The classpath is the list of places the JVM searches to find class files and resources. If a class is not on the classpath, the program fails at runtime even though it compiled.
Detailed Explanation
Java does not link your dependencies into a single executable. A compiled .class file refers to other classes by name, as text, and those names are resolved only when the class is first used. The classpath is the ordered list of directories and JAR files the runtime searches to turn a name like com.acme.billing.Invoice into actual bytes.
This is why Java has a whole family of errors that appear minutes into a running process. NoClassDefFoundError means a class was present when you compiled but is missing now. ClassNotFoundException means something asked for a class by name, usually through reflection, and the loader could not find it. NoSuchMethodError means the class was found but is a different version of it than you compiled against.
There are two classpaths, and confusing them causes most beginner build failures. The compile classpath is what javac reads to type check your code. The runtime classpath is what the JVM reads to execute it. They are usually similar but not identical. A compile-only annotation processor belongs on the first; a JDBC driver you load by name belongs only on the second. Maven scopes (compile, provided, runtime, test) and Gradle configurations (implementation, compileOnly, runtimeOnly) exist precisely to express that difference.
Search order matters, and the rule is first match wins. If two JARs both contain org/slf4j/Logger.class, the one earlier on the classpath is used and the other is silently ignored. That is the "JAR hell" people complain about: your code runs against a version you never chose, with no warning and no error, until a method that only exists in the newer copy gets called.
Class loading itself is delegated in a chain. The application loader asks the platform loader, which asks the bootstrap loader, before any of them look in your JARs. This ordering is what stops a rogue JAR from replacing java.lang.String. Frameworks with their own loaders, like application servers and OSGi containers, deliberately bend this and are a frequent source of "the same class is not the same class" confusion.
The classpath also carries resources, not only code. getResourceAsStream("/config/app.properties") looks through the same list, which is how a properties file bundled inside a JAR is read without knowing a filesystem path.
You set it with -cp/-classpath, or with Class-Path in a JAR manifest, or through your build tool, which is the normal case. The CLASSPATH environment variable also works and is a trap: a stale global value silently overriding a project setting is very hard to diagnose. Since Java 6 you can use wildcards such as -cp "lib/*", which expands to every JAR in that directory but does not recurse.
The cost of the classpath model is weak encapsulation and no version awareness. Every public class in every JAR is visible to everything, and the runtime has no concept of "version 2.1 of this library". JPMS, added in Java 9, addresses the encapsulation half. Build tools with dependency resolution address the version half. Shading and fat JARs are the blunt workaround.
Code Examples
import java.io.InputStream;
import java.util.Properties;
public class ConfigLoader {
public static Properties load() throws Exception {
// Leading slash means "from the classpath root", not the filesystem.
// This works the same whether the file sits in a directory or inside a JAR.
try (InputStream in = ConfigLoader.class.getResourceAsStream("/app.properties")) {
if (in == null) {
throw new IllegalStateException("app.properties is not on the classpath");
}
Properties props = new Properties();
props.load(in);
return props;
}
}
}public class ClasspathDiagnostics {
public static void main(String[] args) throws Exception {
// Print the runtime classpath the JVM was launched with.
System.out.println(System.getProperty("java.class.path"));
// Find out which JAR a class was actually loaded from.
// This is the fastest way to settle a duplicate-dependency argument.
var source = org.slf4j.Logger.class
.getProtectionDomain()
.getCodeSource();
System.out.println(source == null ? "JDK built-in" : source.getLocation());
// prints e.g. file:/Users/you/.m2/repository/org/slf4j/slf4j-api/2.0.13/slf4j-api-2.0.13.jar
}
}Common Gotchas
Compiles fine, dies at runtime
`NoClassDefFoundError` almost always means a dependency is on the compile classpath but not the runtime one. Check the scope in `pom.xml` or the configuration in `build.gradle` before suspecting anything else.
Duplicate classes resolve silently
two versions of the same library on the classpath do not produce a warning. The first one wins. Run `mvn dependency:tree` or `gradle dependencies` and pin the version explicitly.
`CLASSPATH` in your shell profile overrides nothing and breaks everything
passing `-cp` replaces the environment variable, but scripts that omit `-cp` inherit it. Unset the global variable and let your build tool own the list.
A directory entry and a JAR entry behave identically
`-cp build/classes:lib/app.jar` searches the directory tree and the archive with the same package-to-path rules. Package `com.acme` must live in `com/acme` in both.