Sub topic 11
When to Use Module Imports and When Not To
This chapter assumes you know single-type and on-demand imports. It also assumes you have seen import module and know that ambiguity is reported only when a name is used. Earlier chapters covered the syntax, ambiguity and shadowing. Here we turn that mechanics into decisions: where a module import helps, where it hurts, and how to check your choice.
What you are trading
An import module M; declaration behaves like an on-demand import (import pkg.*;) for every package that M exports to your code. That includes packages exported by modules that M re-exports through requires transitive. You give up two things and gain one:
- You gain brevity. One line replaces a block of imports.
- You lose precision. A reader cannot tell from the import list which types the file uses.
- You lose stability. The set of names in scope depends on the JDK version and on the modules on the module path, not only on your source.
Every guideline below follows from that trade.
Where module imports help
Scripts, demos and teaching code
Short programs are read once and thrown away. Import lines add noise and offer little. import module java.base; covers collections, streams, I/O, java.time, java.text, java.math and java.util.function. For a beginner, it removes the question of which package a class lives in.
import module java.base;
public class WordCount {
public static void main(String[] args) {
String text = "to be or not to be";
Map<String, Long> counts = Arrays.stream(text.split(" "))
.collect(Collectors.groupingBy(
Function.identity(), TreeMap::new, Collectors.counting()));
System.out.println(counts);
}
}This file uses Map, Arrays, Collectors, Function and TreeMap. Those come from java.util, java.util.stream and java.util.function. The traditional version needs five import lines, and any one of them can be forgotten.
Code that uses many types from one API
Some APIs spread their types over several packages. The java.net.http module has one package, java.net.http, so a module import saves little there. But java.desktop, java.xml and java.logging each export several packages, and a single line can cover them. If you already use three or more packages from a module in one file, a module import is reasonable.
import module java.base;
import module java.net.http;
public class StatusCheck {
public static void main(String[] args) throws Exception {
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder(URI.create("https://example.com")).build();
HttpResponse<String> response =
client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.statusCode());
}
}URI comes from java.base. HttpClient, HttpRequest and HttpResponse come from java.net.http.
Compact source files and quick experiments
In a compact source file, java.base is already imported implicitly, as the earlier chapter on compact source files explained. You only add import module lines for modules beyond java.base. This is the setting the feature was designed for: small programs where ceremony hides the idea.
Where module imports hurt
Library and application code that is reviewed over time
In a long-lived codebase, the import list documents dependencies. A reviewer sees import java.sql.Connection; and knows the file touches JDBC. With import module java.sql; they learn only that the file may use any of that module's public types. The signal is weaker.
Tools also treat the two forms differently. Many linters, IDE "organize imports" actions and static-analysis rules were written for single-type imports. Check that your team's tooling understands import module before you adopt it widely.
Broad modules next to each other
Importing java.se brings in nearly the whole standard platform. Doing so makes name clashes likely. java.util.Date and java.sql.Date is the classic pair, but there are others, for example java.util.List and java.awt.List. You then fix each clash with a single-type import or a qualified name. If the fixes outnumber the lines you saved, the module import has lost its value.
Sources that must survive JDK upgrades
An on-demand import of any kind can break when a library or the JDK adds a type with the same simple name as one of yours. A module import widens that surface, because a new public type in any exported package of the module counts.
Here is a concrete failure. Your file imports java.base and a third-party module. Both export a type called Result, or a new JDK release adds a type with that name. Your code compiles on one release and fails on the next with an ambiguity error. Single-type imports do not have this problem, because the name is fixed in the import line.
import module java.base;
import module com.example.shapes; // hypothetical: also exports a Result type
public class Report {
// Result r; // would fail to compile if both modules export Result
com.example.shapes.Result r; // qualified name avoids the clash
}For this reason, avoid module imports in code that other teams compile against changing dependencies.
Hidden reliance on transitive exports
import module java.sql; also imports types from java.logging and java.xml, because java.sql declares requires transitive on them. The code compiles, and you may start using Logger without ever having decided to depend on logging. If the upstream module later drops that requires transitive, your file breaks. With explicit imports you would see the dependency in your own code.
Precedence reminder: your own names always win
You do not need to fear your own types being overridden. Module imports sit at the same level as on-demand package imports, which is the lowest precedence. These all take priority over them:
- Types declared in the same file or nested in the enclosing class.
- Types in the same package.
- Single-type imports.
import module java.base;
public class ShadowDemo {
record Path(int x, int y) {} // member type shadows java.nio.file.Path
public static void main(String[] args) {
Path p = new Path(1, 2);
System.out.println(p);
}
}This compiles even though java.base exports java.nio.file.Path. The record declared in the class is closer in scope, so it wins. The cost is that a reader who sees Path may assume the NIO type.
The module readability requirement
In a named module, you can import only modules your module reads. Add the requires first.
module com.example.app {
requires java.sql;
}With this module-info.java, classes in com.example.app may write import module java.sql;. Without the requires, the compiler reports an error. In the unnamed module, which is plain classpath code, the standard platform modules are available by default, so the declaration works without any module-info.java.
Using an import module in a named module does not replace requires. It never adds a dependency. It only changes how names are written.
A decision flow
Practical guidelines
| Situation | Recommendation | Reason |
|---|---|---|
| Single-file script or demo | `import module java.base;` | Least ceremony, low risk |
| Compact source file | Rely on the implicit `java.base` import, add others as needed | `java.base` is already imported |
| Production library | Explicit single-type imports | Documents dependencies, resists upgrades |
| Large application with many contributors | Agree on a team rule, default to explicit | Tooling and review habits |
| File that imports `java.sql` and `java.base` and uses `Date` | Add `import java.util.Date;` or qualify | Single-type import beats module imports |
| Code compiled against several JDK releases | Avoid module imports | Behavior depends on release and flags |
| Named module | Add `requires` first, then import | Module must be read |
A middle path
You can mix styles. Use a module import for the large, familiar module and single-type imports for everything else, including any clashing name.
import module java.base;
import module java.sql;
import java.util.Date;
public class Mixed {
public static void main(String[] args) {
Date now = new Date();
System.out.println(now.getTime() > 0);
}
}The single-type import settles the Date question in one visible line. The rest of the file keeps its short header.
Version status checklist
Before adopting module imports, confirm the JDK that your build and your users actually run.
# JDK 25 and later (feature is final)
javac --release 25 StatusCheck.java
java StatusCheck
# JDK 23 (first preview)
javac --release 23 --enable-preview StatusCheck.java
java --enable-preview StatusCheckA source file using import module does not compile with --release values older than the first preview. Libraries that must support older runtimes therefore cannot use the declaration at all, whatever the style preference.
A review checklist
When you review a change that adds import module, check these points:
- Is the file a script, demo or compact source file, or is it long-lived code?
- Does it import more than one broad module? If so, are there ambiguities that needed fixes?
- Does any type in the file come only through a transitive export that the team has not agreed to depend on?
- Do your tools (formatter, linter, IDE inspections) handle the declaration?
- Which JDK release builds this file, and is the feature final there?
Summary
Module imports reduce the noise of import blocks. They cost you visible dependencies and some stability. Use them where the file is short-lived, where one module dominates, or where the compact source file already sets a light tone. Prefer single-type imports in shared, long-lived code, and resolve every clash with a single-type import or a qualified name. In named modules, always add the requires first, and never treat import module as a way to declare a dependency.
Exercise
A teammate adds import module java.base; and import module java.desktop; to a production service class that uses java.util.List and also a custom Shape list helper. The build passes today. Give two reasons the team might still prefer explicit imports in this file, and show one line that would make List unambiguous if both modules export a List.
Show answer
Reasons: (1) On-demand semantics mean a future JDK or dependency release can add a type that clashes with a name used in the file, so the file may stop compiling after an upgrade. (2) The import list no longer documents which APIs the file depends on, and tooling or reviewers lose that signal. A third valid reason is that java.desktop brings in many packages through requires transitive, widening the name space. To fix the clash, add the single-type import import java.util.List;, which takes precedence over both module imports. (java.awt.List from java.desktop is the type that would otherwise conflict.)
Exercise
You have a named module com.example.tools whose module-info.java is empty apart from the module declaration. A class in it contains import module java.sql; and fails to compile. What is the fix, and why does the unnamed module not need it?
Show answer
Add requires java.sql; to module-info.java. A named module can import only modules it reads, and import module does not create a dependency. Classpath code in the unnamed module reads the platform modules by default, so no requires is needed there.