Sub topic 1
Why Modules: The Problems with the Classpath
Prerequisites
This chapter assumes you know Java packages, access modifiers, javac, java, JAR files, and the classpath. You should also know that a classpath is a list of directories and JAR files that the compiler or JVM searches for classes.
The Java Platform Module System (JPMS) was introduced in Java 9. It addresses problems that become difficult to manage as an application grows or uses many libraries.
The classpath is a flat search path
On the classpath, every class is effectively part of one large namespace. A class can be public and still be intended only for a library's internal use. The classpath does not express that difference.
The JVM searches classpath entries in order. If two JAR files contain the same fully qualified class name, the first matching class usually wins. This can make behavior depend on command-line order rather than on a declared dependency rule.
java -cp old-api.jar:new-api.jar com.example.app.Main
java -cp new-api.jar:old-api.jar com.example.app.MainThese commands can load different versions of the same class. The application may compile successfully and then fail with NoSuchMethodError when the selected version does not contain the method that the application expects.
| Classpath problem | Typical result |
|---|---|
| Duplicate classes in different JAR files | The classpath order decides which class loads |
| Missing indirect dependency | Failure appears during compilation or startup |
| Public internal packages | Other code can depend on implementation details |
| Incompatible library versions | Runtime linkage errors such as `NoSuchMethodError` |
| Large dependency set | Configuration becomes difficult to inspect |
What modules add
A module is a named group of packages with a descriptor named module-info.java. The descriptor declares dependencies and the packages that form the module's supported API.
A module can require another module and export only selected packages. The compiler and JVM can then resolve a module graph before the application starts. A package that is present but not exported is not part of another module's accessible API.
module com.example.orders {
requires com.example.billing;
exports com.example.orders.api;
}This descriptor says that com.example.orders depends on com.example.billing, but it exposes only com.example.orders.api. Its other packages remain encapsulated from ordinary access by other named modules.
The design goal
JPMS provides a controlled namespace, explicit dependencies, and stronger encapsulation. These rules help large applications evolve without accidentally exposing every implementation package.
Exercise
Why can two classpath entries containing the same class produce different behavior?
Show answer
The JVM searches entries in order and loads the first matching class, so changing the order can select a different version.