Sub topic 8
The Modular JDK and `java.base`
Assume you know Java packages, javac, java, JAR files, and basic module descriptors. This chapter focuses on the JDK modules that provide Java’s standard library, especially the root module java.base.
The JDK is divided into modules
Before Java 9, the JDK was commonly treated as one large collection of classes. The Java Platform Module System divides the platform into named modules. Examples include:
| Module | Main purpose |
|---|---|
| `java.base` | Core language, collections, I/O, networking, and other fundamental APIs |
| `java.sql` | JDBC database access |
| `java.xml` | XML processing |
| `java.desktop` | AWT, Swing, and desktop APIs |
java.base is the root of the standard module graph. Every named module reads it automatically. Therefore, a module descriptor must not declare requires java.base;.
module com.example.app {
requires java.sql;
}This module can use classes from java.sql and from java.base. For example, String, List, and System come from java.base, while java.sql.Connection comes from java.sql.
Reading the JDK module graph
A module is readable when the Java compiler or runtime allows it to access another module. The requires directive creates that relationship. The JDK's modules use the same rules as application modules.
You can inspect the modules in the running JDK:
java --list-modulesTo inspect one module in detail:
java --describe-module java.baseThe output includes the module name, version, exported packages, provided services, and required modules. You can also inspect the module used by a particular Java installation:
java -version
javac -versionUse matching commands from the same JDK installation. A common error is compiling with one JDK and running with another, which can produce missing-module or unsupported-version errors.
`java.base` and encapsulation
java.base exports public API packages such as java.lang, java.util, and java.io. Exporting a package makes its public and protected types available to readable modules.
Internal JDK packages are not general-purpose API. Strong encapsulation prevents ordinary application code from accessing them through reflection. Code that depends on internal packages may fail after moving from the classpath to the module path.
A module can require another JDK module explicitly:
module com.example.reporting {
requires java.sql;
exports com.example.reporting.api;
}It does not need to declare java.base, because the module system supplies that dependency automatically.
Exercise
Why does a module that uses java.util.List not need requires java.base;?
Show answer
Every named module has an implicit dependency on java.base, which exports the java.util package.