Course contentsShow
← Java
Lesson 690 of 2,87016. Packages, Imports, and JAR FilesFree lesson

Setting the Classpath with -cp and -classpath

Using the -cp or -classpath option with java and javac to specify where to find compiled classes and JAR dependencies.

Setting the Classpath with -cp and -classpath

You'll learn how to tell Java exactly where to find your compiled classes and JAR files when running or compiling programs.

The Core Idea

Think of the classpath as a roadmap for Java: it tells the JVM and compiler where to look for .class files and JAR files. Without this roadmap, Java won't know where your packaged classes or external libraries live, even if they're on your hard drive.

Both javac (the compiler) and java (the runtime) accept the -cp or -classpath option to specify this search path. These two flags are identical—-cp is just shorthand.

Using -cp with javac

When compiling, you might need classes from other packages or JARs:

javac -cp /path/to/dependencies MyProgram.java

This tells the compiler where to find any classes MyProgram depends on.

Using -cp with java

When running your program, you must tell Java where to find all classes—yours and any dependencies:

java -cp /path/to/classes com.mycompany.MyProgram

Multiple Locations

You can specify multiple directories or JAR files by separating them with a delimiter:

  • Windows: semicolon (;)
  • Linux/Mac: colon (:)
# Linux/Mac
java -cp /path/to/classes:/path/to/lib.jar com.mycompany.MyProgram

# Windows
java -cp C:\path\to\classes;C:\path\to\lib.jar com.mycompany.MyProgram

The Current Directory

Use . to include the current directory in your classpath:

java -cp .:lib/mylib.jar com.mycompany.MyProgram

Key Takeaway: Use -cp or -classpath with java and javac to specify where to find compiled classes and JAR dependencies—it's your explicit roadmap for Java's class-loading system.