Classpath Order and Class Loading Precedence
You'll learn: How the JVM searches for classes in the exact order you specify on the classpath, and what happens when multiple JARs contain the same class.
How the JVM Searches the Classpath
When the JVM needs to load a class, it searches through the classpath entries from left to right, stopping immediately at the first matching class it finds. This is called the first-match-wins rule.
Think of it like looking for a book in a stack of libraries: you check the first library, then the second, then the third. As soon as you find the book, you stop searching—even if other libraries might have different editions.
Classpath Order Matters
When you set your classpath like this:
java -cp lib1.jar:lib2.jar:lib3.jar MyApp
The JVM searches lib1.jar first, then lib2.jar, then lib3.jar. If lib1.jar and lib3.jar both contain com.example.Util, the JVM will always load the version from lib1.jar and never even look at the one in lib3.jar.
The Duplicate Class Problem
This precedence rule creates a critical implication: if you accidentally include multiple versions of the same library, or if two dependencies bundle the same classes, you might not be using the version you expect. The "wrong" version might load first, leading to subtle bugs or NoSuchMethodError exceptions if method signatures differ between versions.
Controlling What Loads
To ensure the correct version loads, place the desired JAR earlier in the classpath order. Directory entries work the same way—they're searched in order with JARs.
Key Takeaway: The JVM searches the classpath left-to-right and stops at the first matching class; carefully ordering classpath entries prevents loading incorrect versions of duplicate classes.