Java Classpath: How -cp and CLASSPATH Find Your Classes

Su Suriya Ravichandran Updated 18 Nov 2026
9 min read ·Lesson 232 of 306

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 itExampleScope
-cp / -classpath / --class-pathjava -cp classes com.gocourse.shop.HelloOne command
CLASSPATH environment variableexport CLASSPATH=classesEvery command in that shell that has no -cp
Class-Path in a JAR manifestClass-Path: lib/tax-lib-1.0.jarOnly when run with java -jar
Nothing setDefaults to the current folder (.)
Entry typeExampleWhat the JVM searches
Folder of .class filesclassesclasses/com/gocourse/shop/Hello.class for com.gocourse.shop.Hello
JAR filelib/tax-lib-1.0.jarThe package path inside the JAR
Wildcardlib/*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;lib0".


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 classes writes classes/com/gocourse/shop/Hello.class, creating one folder per package part.
  • -cp classes tells the JVM to start searching in classes. It turns the class name com.gocourse.shop.Hello into the path com/gocourse/shop/Hello.class and 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 java is always the fully qualified name with dots, never a file path. java -cp classes com/gocourse/shop/Hello.class is 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=classes would set it for the whole session.
  • -cp replaces CLASSPATH; the two are not merged.

Note: A global CLASSPATH set years ago in a system profile is a common cause of confusing "wrong class loaded" bugs. Prefer -cp on 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, javac needs the libraries to check that TaxCalculator.gst(double) and Money.format(double) exist.
  • At run time, the JVM loads Checkout from classes and the library classes from the two JARs.
  • 2500 × 0.18 = 450, and 2500 + 450 = 2950. The %,.2f pattern 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 ruleDetail
lib/*Matches .jar and .JAR files directly inside lib
SubfoldersNot searched: lib/extra/x.jar is not included
.class filesNot matched; use lib (without *) for a folder of classes
lib/*.jarNot valid; only a bare * is supported
QuotesNeeded, 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.

ClassNotFoundExceptionNoClassDefFoundError
TypeChecked exceptionError
WhenCode asks for a class by name, e.g. Class.forName("..."), or the main class is missingA class that was present at compile time is missing at run time
Typical causeTypo in a class name, or a driver/plugin JAR not on the classpathA library JAR left off the runtime classpath
Should you catch it?Often, when a class is optionalRarely; 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.forName searches the classpath at run time for a class name stored in a string. The compiler cannot check the name, so the method declares the checked ClassNotFoundException.
  • 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:

  1. Class-Path in the manifest. It lists JARs separated by spaces, relative to the location of shop-app.jar itself, not to the current folder. That is why lib/... works from any directory.
  2. java.class.path shows 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 from dist/lib.
  3. The numbers. 1499 + 349 = 1848; 1848 × 0.18 = 332.64; the total is 2180.64.
  4. -jar ignores -cp. With java -jar, the JAR and its manifest define the whole classpath, and both -cp and CLASSPATH are ignored. The missing Money class is reported only when line 19 first uses it, the classic NoClassDefFoundError.
  5. 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.

0 Comments

Reviewed before they appear

No comments yet.

Java
Java Introduction Java Features Java Syntax Java Comments Java Statements Java Output Java Variables Java Data Types Java Type Casting Java Operators Java Strings Java Numbers Java Math Java Booleans Java User Input Java Conditions Java If Else Java Switch Java While Loop Java For Loop Java Break Java Continue Java Arrays Java Methods Java Parameters Java Return Values Java Scope Java Recursion Install Java Install JDK Java IDEs Java JDK Java JRE Java JVM Java Compiler Java File Compile Java Run Java JShell Basics Java Packages Java OOP Java Classes Java Objects Class Methods Constructors Constructor Overload this Keyword static Keyword final Keyword Encapsulation Inheritance Polymorphism Abstraction Access Modifiers super Keyword Method Overload Method Override Instanceof Operator Nested Classes Inner Classes Anonymous Classes Enums Records Array Basics Array Length Loop Arrays Multidimensional Arrays Array Copy Array Sorting Array Search ArrayList LinkedList HashSet TreeSet HashMap TreeMap Queue Interface Deque Interface Stack Class Iterator List Interface Set Interface Map Interface Collections Class Comparable Comparator Generics Basics Generic Classes Generic Methods Wildcards String Basics String Length String Methods String Concatenation String Compare String Search String Replace String Split String Format StringBuilder StringBuffer Text Blocks Regular Expressions Number Types Integer Class Float Class Double Class BigInteger BigDecimal Math Class Random Numbers Number Format Date Basics LocalDate LocalTime LocalDateTime ZonedDateTime Date Formatting Date Parsing Period Class Duration Class Java Instant Class Java Exception Basics Java try...catch Java Multiple Catch Blocks Java finally Block Java throw Keyword Java throws Keyword Java Checked Exceptions Java Unchecked Exceptions Java Custom Exceptions Java try-with-resources Java Exception Chaining Java File Basics Java Create Files Java Read Files Java Write Files Java Delete Files Java File Paths Java File Class Java BufferedReader Java BufferedWriter Java FileInputStream Java FileOutputStream Java Object Streams Java Directory Handling Java NIO Basics Java Files API Java Input Java Scanner Class Java Console Input Java PrintStream Java InputStream Java OutputStream Java Reader Class Java Writer Class Java Buffered Streams Java Data Streams Java Generics Introduction Java Generic Types Java Generic Methods Java Bounded Types Java Wildcards Java Type Erasure Java Generic Interfaces Java Generic Collections Java Lambda Basics Java Lambda Syntax Java Functional Interfaces Java Method References Java Stream API Java Stream Creation Java Stream Filter Java Stream Map Java Stream Reduce Java Stream Sort Java Stream Collect Java Collectors Class Java Optional Class Java Parallel Streams Java Threads: Thread Basics Create a Thread in Java Java Thread Class Java Runnable Interface Java Thread States Java Thread Sleep Java Thread Join Java Thread Priority Java Synchronization Java Thread Safety Java Race Conditions Java Deadlocks Java Executor Service Java Thread Pools Java Callable Interface Java Future Interface Java CompletableFuture Java Concurrent Collections Java Atomic Classes Java Virtual Threads Java Networking Basics Java URL Class Java URI Class Java HttpClient Java HTTP Requests Java HTTP Responses Java Socket Basics Java ServerSocket Java DatagramSocket Java WebSocket Basics Java JDBC Basics Java JDBC Setup Java Database Connection Java JDBC Connection Interface Java JDBC Statement Java PreparedStatement Java ResultSet Java JDBC CRUD Operations Java JDBC Transactions Java JDBC Batch Update Java Connection Pooling with HikariCP Java JPA Basics: Entities, EntityManager and JPQL Java Hibernate Basics: SessionFactory, Session and HQL Package in Java: Basics Explained with Examples Create Package in Java: Step-by-Step Guide with Examples Import Package in Java: The import Statement Explained Access Control in Java: Packages, Classes and Members JAR File in Java: Create, Run and Inspect JAR Files Java Modules: Introduction to the Java Module System module-info in Java: Every Module Directive Explained Java Module Path: How --module-path Finds Your Modules Java Classpath: How -cp and CLASSPATH Find Your Classes Java Annotations: Basics of @ Metadata in Java Java Built-in Annotations: @Override, @Deprecated and More Java Custom Annotations: Create Your Own @interface Java Annotation Targets: @Target and ElementType Explained Java Reflection API: Inspect and Use Classes at Runtime Java Class Metadata: Names, Modifiers, Hierarchy and Generic Java Dynamic Objects: Create Objects Dynamically With Reflec Java Dynamic Proxy: Intercept Method Calls With Proxy and In Java Security Java Secure Coding Java Password Hashing Java Input Validation Java Cryptography Basics Java KeyStore Basics Java TLS Basics Java SecureRandom Java JUnit Basics Java JUnit Test Methods JUnit Assertions JUnit Test Fixtures JUnit Parameterized Tests Mockito in Java Java Mock Objects Java Integration Testing Java Code Coverage Maven in Java Create a Maven Project in Java Maven Dependencies Maven Plugins Gradle in Java Gradle Build Gradle Dependencies Build Executable JAR in Java Build WAR File in Java HTTP Basics in Java Java Servlet Basics Servlet Lifecycle in Java HttpServletRequest in Java HttpServletResponse in Java JSP in Java JSTL in JSP REST API in Java JSON in Java Java Web Application Spring Framework Basics Spring Boot Tutorial Spring MVC Spring Data JPA Spring Security Spring Boot REST API Jakarta EE Basics Java Deployment JAR Deployment Java WAR Deployment Run Java as a Service Docker Java: Dockerize a Java Application Java Environment Variables and Configuration Java Logging Basics Java Production Setup Java JVM Options Java JVM Monitoring Java Hello World App Java Calculator App Java Number Guess Game Java Student Manager Java Library System Java Bank App Java Todo App Java File Manager Java Quiz App Java REST API Project Java Chat Server Java Employee Manager Java E-commerce API
Ask about this post
AI Ask about this post

Ask questions about Java Classpath: How -cp and CLASSPATH Find Your Classes and get answers drawn from it.

Signed-in readers only.