Classpath Mechanics: How the JVM Finds Classes
You'll learn how the traditional classpath system locates and loads classes, and why its limitations sparked the creation of JPMS.
How the Classpath Works
The classpath is a list of directories and JAR files where the JVM searches for .class files when your program runs. Think of it like a library catalog: when your code references a class, the JVM consults this list in order until it finds a match.
Search Order and Loading
When you launch Java with -classpath (or -cp), the JVM searches locations left to right:
- Checks the first classpath entry for the requested class
- If not found, moves to the next entry
- Loads the first match it finds and stops searching
- If no match exists anywhere, throws
ClassNotFoundException
This "first-wins" approach creates a crucial limitation: you cannot control which version of a duplicate class loads if multiple JARs contain the same fully-qualified class name.
The Problems That Led to JPMS
The classpath model has several flaws:
- No encapsulation: All public classes in all JARs are globally accessible
- JAR Hell: Conflicting versions of the same library cause unpredictable behavior
- No explicit dependencies: The JVM doesn't know what your application needs until runtime failure occurs
- Fragile configurations: Missing JARs only surface when code paths execute
These issues become severe in large applications with dozens or hundreds of dependencies, where version conflicts and visibility problems create maintenance nightmares.
Key Takeaway: The classpath uses first-match linear search with no encapsulation or dependency tracking, creating "JAR Hell" scenarios that JPMS solves through explicit module declarations and strong encapsulation.