Java Classpath: How -cp and CLASSPATH Find Your Classes
The Java classpath is the list of folders and JAR files where the compiler and the JVM search for classes that are not part of the JDK. Every time your code uses a class from your own project or from a library, the class loader looks for it on the classpath.
You set the classpath with -cp (or -classpath / --class-path) or with the CLASSPATH environment variable. This lesson shows how to set it, how the search order works, how to load all JARs in a folder with lib/*, and how to fix ClassNotFoundException and NoClassDefFoundError. It is the counterpart of the Java Module Path from the previous lesson.
Java Classpath Syntax
# compile against libraries
javac -d classes -cp <entry1>:<entry2> <source files>
# run a main class
java -cp <entry1>:<entry2> <fully.qualified.MainClass>
| Way to set it | Example | Scope |
|---|---|---|
-cp / -classpath / --class-path | java -cp classes com.gocourse.shop.Hello | One command |
CLASSPATH environment variable | export CLASSPATH=classes | Every command in that shell that has no -cp |
Class-Path in a JAR manifest | Class-Path: lib/tax-lib-1.0.jar | Only when run with java -jar |
| Nothing set | Defaults to the current folder (.) |
| Entry type | Example | What the JVM searches |
|---|---|---|
Folder of .class files | classes | classes/com/gocourse/shop/Hello.class for com.gocourse.shop.Hello |
| JAR file | lib/tax-lib-1.0.jar | The package path inside the JAR |
| Wildcard | lib/* | Every .jar file in lib (not subfolders) |
Note: Entries are separated by
:on Linux and macOS and by;on Windows. On Windows write-cp "classes;lib 0 ".
Running a Class With -cp
A class in package com.gocourse.shop must live in the matching folders. The classpath points at the root of that folder tree, not at the package folder.
package com.gocourse.shop;
public class Hello {
public static void main(String[] args) {
System.out.println("Hello from the classpath!");
System.out.println("java.class.path = " + System.getProperty("java.class.path"));
}
}
javac -d classes src/com/gocourse/shop/Hello.java
java -cp classes com.gocourse.shop.Hello
Output:
Hello from the classpath!
java.class.path = classes
How it works:
javac -d classeswritesclasses/com/gocourse/shop/Hello.class, creating one folder per package part.-cp classestells the JVM to start searching inclasses. It turns the class namecom.gocourse.shop.Hellointo the pathcom/gocourse/shop/Hello.classand finds the file.System.getProperty("java.class.path")returns the classpath the JVM actually used, which is handy for debugging.
The Default Classpath Is the Current Folder
With no -cp and no CLASSPATH, the classpath is .. Running from inside classes works; running from the project root does not:
cd classes && java com.gocourse.shop.Hello
Hello from the classpath!
java.class.path = .
java com.gocourse.shop.Hello # from the project root
Error: Could not find or load main class com.gocourse.shop.Hello
Caused by: java.lang.ClassNotFoundException: com.gocourse.shop.Hello
Note: The class name passed to
javais always the fully qualified name with dots, never a file path.java -cp classes com/gocourse/shop/Hello.classis wrong. See Package in Java for how packages map to folders.
Setting the CLASSPATH Environment Variable
The CLASSPATH variable sets a default for every java and javac command in the current shell.
CLASSPATH=classes java com.gocourse.shop.Hello
Output:
Hello from the classpath!
java.class.path = classes
When both are present, -cp wins and CLASSPATH is ignored completely:
CLASSPATH=nowhere java -cp classes com.gocourse.shop.Hello
Hello from the classpath!
java.class.path = classes
How it works:
CLASSPATH=classes java ...sets the variable only for that one command.export CLASSPATH=classeswould set it for the whole session.-cpreplacesCLASSPATH; the two are not merged.
Note: A global
CLASSPATHset years ago in a system profile is a common cause of confusing "wrong class loaded" bugs. Prefer-cpon the command line or a build tool, so every project states its own classpath.
Adding Library JARs to the Classpath
Real programs use libraries. Here, two small libraries are packaged as JARs:
package com.gocourse.tax;
public final class TaxCalculator {
private TaxCalculator() { }
public static double gst(double amount) {
return amount * 0.18;
}
public static String version() {
return "tax-lib 1.0";
}
}
package com.gocourse.money;
public final class Money {
private Money() { }
public static String format(double amount) {
return String.format("Rs. %,.2f", amount);
}
}
javac -d lib1out lib1src/com/gocourse/tax/TaxCalculator.java
jar --create --file lib/tax-lib-1.0.jar -C lib1out .
javac -d lib2out lib2src/com/gocourse/money/Money.java
jar --create --file lib/money-lib-2.3.jar -C lib2out .
The application uses both:
package com.gocourse.shop;
import com.gocourse.money.Money;
import com.gocourse.tax.TaxCalculator;
public class Checkout {
public static void main(String[] args) {
double subtotal = 2500.00;
double tax = TaxCalculator.gst(subtotal);
System.out.println("Subtotal: " + Money.format(subtotal));
System.out.println("GST 18%: " + Money.format(tax));
System.out.println("Total: " + Money.format(subtotal + tax));
}
}
The libraries must be on the classpath both when compiling and when running. When running, your own classes folder must be there too:
javac -d classes -cp lib/tax-lib-1.0.jar:lib/money-lib-2.3.jar src/com/gocourse/shop/Checkout.java
java -cp classes:lib/tax-lib-1.0.jar:lib/money-lib-2.3.jar com.gocourse.shop.Checkout
Output:
Subtotal: Rs. 2,500.00
GST 18%: Rs. 450.00
Total: Rs. 2,950.00
How it works:
- At compile time,
javacneeds the libraries to check thatTaxCalculator.gst(double)andMoney.format(double)exist. - At run time, the JVM loads
Checkoutfromclassesand the library classes from the two JARs. 2500 × 0.18 = 450, and2500 + 450 = 2950. The%,.2fpattern adds the thousands separator.
Using a Wildcard: lib/*
Listing every JAR gets long. A * at the end of an entry adds every .jar file in that folder:
java -cp "classes:lib/*" com.gocourse.shop.Checkout
Output:
Subtotal: Rs. 2,500.00
GST 18%: Rs. 450.00
Total: Rs. 2,950.00
| Wildcard rule | Detail |
|---|---|
lib/* | Matches .jar and .JAR files directly inside lib |
| Subfolders | Not searched: lib/extra/x.jar is not included |
.class files | Not matched; use lib (without *) for a folder of classes |
lib/*.jar | Not valid; only a bare * is supported |
| Quotes | Needed, so the shell does not expand * itself |
Note: The order of JARs matched by
*is not guaranteed. If the order matters (see the next section), list those JARs explicitly.
Classpath Order: The First Match Wins
The JVM searches classpath entries from left to right and loads the first class it finds with the requested name. Later copies are silently ignored. Put a second version of the tax library, tax-lib-2.0.jar, in an old folder and run a program that reports which copy it used:
package com.gocourse.shop;
import com.gocourse.tax.TaxCalculator;
public class WhichJar {
public static void main(String[] args) {
System.out.println("Version: " + TaxCalculator.version());
System.out.println("Loaded from: "
+ TaxCalculator.class.getProtectionDomain().getCodeSource().getLocation());
}
}
java -cp "classes:lib/tax-lib-1.0.jar:old/tax-lib-2.0.jar" com.gocourse.shop.WhichJar
java -cp "classes:old/tax-lib-2.0.jar:lib/tax-lib-1.0.jar" com.gocourse.shop.WhichJar
Output (paths shortened):
Version: tax-lib 1.0
Loaded from: file:/.../lib/tax-lib-1.0.jar
Version: tax-lib 2.0
Loaded from: file:/.../old/tax-lib-2.0.jar
How it works:
- Both JARs contain
com/gocourse/tax/TaxCalculator.class. Swapping their order swaps which one is used, with no warning. getProtectionDomain().getCodeSource().getLocation()returns the JAR or folder a class came from. Use it whenever you suspect the wrong version of a library is loaded.- This silent "shadowing" is one of the problems the module path solves: there, duplicate packages are an error.
ClassNotFoundException vs NoClassDefFoundError
Both errors mean "a class was not found on the classpath", but they appear in different situations.
ClassNotFoundException | NoClassDefFoundError | |
|---|---|---|
| Type | Checked exception | Error |
| When | Code asks for a class by name, e.g. Class.forName("..."), or the main class is missing | A class that was present at compile time is missing at run time |
| Typical cause | Typo in a class name, or a driver/plugin JAR not on the classpath | A library JAR left off the runtime classpath |
| Should you catch it? | Often, when a class is optional | Rarely; fix the classpath instead |
NoClassDefFoundError: Missing JAR at Run Time
Compile Checkout with both libraries, then forget the tax library when running:
java -cp "classes:lib/money-lib-2.3.jar" com.gocourse.shop.Checkout
Output:
Exception in thread "main" java.lang.NoClassDefFoundError: com/gocourse/tax/TaxCalculator
at com.gocourse.shop.Checkout.main(Checkout.java:9)
Caused by: java.lang.ClassNotFoundException: com.gocourse.tax.TaxCalculator
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:641)
...
The program starts normally and fails only at line 9, the first line that touches TaxCalculator. The compiler would have caught it earlier:
javac -d tmp src/com/gocourse/shop/Checkout.java
src/com/gocourse/shop/Checkout.java:3: error: package com.gocourse.money does not exist
import com.gocourse.money.Money;
^
ClassNotFoundException: Loading a Class by Name
package com.gocourse.shop;
public class LoadByName {
public static void main(String[] args) {
String[] classNames = {"com.gocourse.tax.TaxCalculator", "com.gocourse.payments.UpiGateway"};
for (String className : classNames) {
try {
Class<?> found = Class.forName(className);
System.out.println("Found: " + found.getName());
} catch (ClassNotFoundException e) {
System.out.println("Missing: " + e.getMessage());
}
}
}
}
java -cp "classes:lib/*" com.gocourse.shop.LoadByName
Output:
Found: com.gocourse.tax.TaxCalculator
Missing: com.gocourse.payments.UpiGateway
How it works:
Class.forNamesearches the classpath at run time for a class name stored in a string. The compiler cannot check the name, so the method declares the checkedClassNotFoundException.- Catching it lets the program continue without an optional feature, the same idea JDBC used to load database drivers by name.
Real-World Example: Executable JAR With a Class-Path Manifest
Typing a long -cp for every user is impractical. An executable JAR can carry its classpath in its manifest, as introduced in JAR File in Java. This example ships a shop app with two library JARs in a lib folder next to it.
dist/
├── shop-app.jar
└── lib/
├── tax-lib-1.0.jar
└── money-lib-2.3.jar
ShopApp.java calculates a cart total and prints its own classpath and where each library class came from:
package com.gocourse.shop;
import com.gocourse.money.Money;
import com.gocourse.tax.TaxCalculator;
import java.io.File;
import java.util.List;
import java.util.Map;
public class ShopApp {
public static void main(String[] args) {
printClasspath();
Map<String, Double> cart = Map.of("Java Course", 1499.00, "DSA Workbook", 349.00);
double subtotal = cart.values().stream().mapToDouble(Double::doubleValue).sum();
double tax = TaxCalculator.gst(subtotal);
System.out.println();
System.out.println("Subtotal: " + Money.format(subtotal));
System.out.println("GST 18%: " + Money.format(tax));
System.out.println("Total: " + Money.format(subtotal + tax));
System.out.println();
for (Class<?> libraryClass : List.of(TaxCalculator.class, Money.class)) {
System.out.printf("%-14s <- %s%n", libraryClass.getSimpleName(),
libraryClass.getProtectionDomain().getCodeSource().getLocation());
}
}
private static void printClasspath() {
String classpath = System.getProperty("java.class.path");
System.out.println("Classpath entries:");
for (String entry : classpath.split(File.pathSeparator)) {
System.out.println(" " + entry);
}
}
}
manifest.txt:
Main-Class: com.gocourse.shop.ShopApp
Class-Path: lib/tax-lib-1.0.jar lib/money-lib-2.3.jar
Build and run:
javac -d appclasses -cp "lib/*" src/com/gocourse/shop/ShopApp.java
mkdir -p dist/lib && cp lib/*.jar dist/lib/
jar --create --file dist/shop-app.jar --manifest manifest.txt -C appclasses .
cd dist && java -jar shop-app.jar
Output (paths shortened):
Classpath entries:
shop-app.jar
Subtotal: Rs. 1,848.00
GST 18%: Rs. 332.64
Total: Rs. 2,180.64
TaxCalculator <- file:/.../dist/lib/tax-lib-1.0.jar
Money <- file:/.../dist/lib/money-lib-2.3.jar
Now delete dist/lib/money-lib-2.3.jar and try to "fix" it with -cp:
java -cp "lib/*" -jar dist/shop-app.jar
Classpath entries:
dist/shop-app.jar
Exception in thread "main" java.lang.NoClassDefFoundError: com/gocourse/money/Money
at com.gocourse.shop.ShopApp.main(ShopApp.java:19)
Caused by: java.lang.ClassNotFoundException: com.gocourse.money.Money
...
How it works:
Class-Pathin the manifest. It lists JARs separated by spaces, relative to the location ofshop-app.jaritself, not to the current folder. That is whylib/...works from any directory.java.class.pathshows only the main JAR. Manifest entries are added by the class loader behind the scenes, but the code-source locations prove both libraries were loaded fromdist/lib.- The numbers.
1499 + 349 = 1848;1848 × 0.18 = 332.64; the total is2180.64. -jarignores-cp. Withjava -jar, the JAR and its manifest define the whole classpath, and both-cpandCLASSPATHare ignored. The missingMoneyclass is reported only when line 19 first uses it, the classicNoClassDefFoundError.- The fix. Put the missing JAR back in
dist/lib, or run without-jar:java -cp "dist/shop-app.jar:lib/*" com.gocourse.shop.ShopApp.
Build tools such as Maven and Gradle generate these classpaths for you, but they use exactly the rules shown in this lesson, so knowing them makes build errors much easier to read.