The Classpath: Finding Classes at Runtime
You'll learn how the JVM locates your compiled .class files and JAR archives when your program runs.
What Is the Classpath?
The classpath is a list of locations that tells the Java Virtual Machine (JVM) where to search for class files when your program executes. Think of it like a search path—similar to how your operating system uses PATH to find executable programs, Java uses the classpath to find .class files and JAR archives.
Without the classpath, the JVM wouldn't know where to look for the classes your program needs, including both your own code and third-party libraries.
How the Classpath Works
When you run a Java program, the JVM searches through the classpath in order, looking in:
- Directories containing
.classfiles (organized by package structure) - JAR files (which are archives of
.classfiles)
The JVM stops searching once it finds the first matching class.
Setting the Classpath
You can specify the classpath in two ways:
Using the -cp or -classpath flag:
java -cp /path/to/classes:/path/to/library.jar com.example.Main
Using the CLASSPATH environment variable (less common, flag takes precedence)
Multiple Locations
Separate multiple classpath entries with:
- Colon (
:) on Linux/Mac - Semicolon (
;) on Windows
The current directory (.) is not included automatically unless you add it explicitly.
Key Takeaway: The classpath tells the JVM where to search for .class files and JAR files at runtime—you specify it using the -cp flag or CLASSPATH environment variable, with multiple locations separated by platform-specific delimiters.