Sub topic 3
Using Java Module Imports in a Named Module
This chapter assumes you can compile Java classes, use package imports, and recognize requires in module-info.java.
Using module imports inside a named module
A named module must read another module before its source files can import that module. Declare the dependency with requires, then use import module:
// module-info.java
module com.example.app {
requires java.sql;
}// Report.java
import module java.sql;
public class Report {
public static void main(String[] args) {
Date today = new Date(System.currentTimeMillis());
System.out.println(today);
}
}The java.sql module exports java.sql.Date, so the module import makes Date available. The import does not add a dependency. requires java.sql; does that.
requires transitive affects other modules that read your module. It does not make an imported module readable by itself.
Compiling and running across JDK versions
Module import declarations were preview features in JDK 23 and JDK 24. Use a matching --release and enable preview features:
javac --release 23 --enable-preview module-info.java Report.java
java --enable-preview ReportThe feature became final in JDK 25. JDK 25 and later need no preview flag:
javac --release 25 module-info.java Report.java
java ReportCompact source files
A compact source file implicitly imports the java.base module. Therefore, common types such as String, List, and System can be used without writing import module java.base;. This implicit import applies only to java.base, not to modules such as java.sql.
When to use module imports
Module imports reduce many repetitive imports in small programs, examples, and learning exercises. They can also make a source file easier to start.
They may expose many names and create collisions, especially when importing several modules. Explicit imports document the exact dependencies and make name conflicts easier to spot.
Exercise
What must a named module declare before its source file can use import module java.sql;?
Show answer
It must read the module with requires java.sql; in module-info.java.