Sub topic 3
The import module declaration
This chapter covers the syntax of import module, what the compiler does with it, and how to compile and run code that uses it. You should be comfortable with single-type imports (import java.util.List;) and on-demand imports (import java.util.*;), and know what a package and a fully qualified name are. It helps to know what module-info.java and requires do, but you don't need to.
What problem it solves
A typical Java file starts with a block of imports. Code that uses collections, streams, I/O and time types can easily need ten or more lines, and an IDE usually writes them for you. When you write a short program by hand, or paste an example into a chat or a tutorial, that block is noise.
Java already lets you collapse it with on-demand imports such as import java.util.*;. That covers one package at a time. The java.base module alone exports dozens of packages. A module import goes one level up. It imports every package that a module exports, with a single line.
The syntax
A module import declaration has this form:
import module java.base;It has three parts:
- The keywords
import module. - A module name. This can be a dotted name such as
java.sql. Wildcards such asjava.*are not allowed. - A closing semicolon.
You write it in the same place as other imports: after the optional package declaration and before the first class, interface, enum or record. You can mix it freely with other kinds of imports, and the order does not matter for correctness.
Here is a complete program that uses one module import in place of four ordinary imports:
import module java.base;
public class ModuleImportDemo {
public static void main(String[] args) {
List<String> names = List.of("Ada", "Grace", "Alan");
Map<String, Integer> lengths = new HashMap<>();
for (String name : names) {
lengths.put(name, name.length());
}
String joined = names.stream()
.sorted()
.collect(Collectors.joining(", "));
System.out.println(joined);
System.out.println(lengths.get("Grace"));
}
}List, Map and HashMap come from java.util. Collectors comes from java.util.stream. Both packages are exported by java.base, so the simple names work. The program prints Ada, Alan, Grace and then 5.
Without the module import, you would write import java.util.List;, import java.util.Map;, import java.util.HashMap; and import java.util.stream.Collectors;. Or you would use two on-demand imports.
What the declaration makes visible
The compiler treats import module M; as if you had written an on-demand import for each package in a certain set. A type from a package in that set is visible by its simple name if it meets all of these conditions:
- Its package is exported by module
M. The export must be unconditional, or qualified so that it names the module containing your code. - It is a top-level class, interface, enum, record or annotation interface.
- It is
public. Package-private types in an exported package are not part of its API, and they are not imported.
The set also includes packages exported by modules that M reads through requires transitive. A later chapter covers that mechanism in detail.
Because the diagram fence must name its type exactly, here is the same flow in the required form:
Several details follow from these rules.
Subpackages are not included automatically. An on-demand import of java.util.* does not import java.util.stream.Collectors, because java.util.stream is a different package. A module import does not have this problem for exported packages, because each exported package is imported on its own. java.util.stream is exported by java.base, so Collectors is visible. A package that the module does not export is not visible, even if its name starts with an exported package's name.
Nested types are not imported by simple name. Map.Entry is a member of Map. After a module import you can write Map.Entry, but not plain Entry. To use Entry alone, add import java.util.Map.Entry;.
Only types are imported. Module imports do not import static members such as Math.max. For those you still need import static.
Nothing happens at run time. Imports are a compile-time convenience. The compiled class file refers to types by their full names, so import module adds no cost and no new dependency. It does not add a module to the module graph. It only lets you write short names for modules that are already there.
Which modules you can import
The compiler must be able to find the module you name. If it can't, you get a compile-time error such as "module not found". Which modules are available depends on where your code lives.
- Code in an unnamed module. This is the normal case for single-file programs and for classes compiled without a
module-info.java. All system modules that are in the default module graph are available.java.baseis always there. Modules such asjava.sql,java.net.httporjava.desktopare normally there too when you run on a full JDK. - Code in a named module. The module that holds your source file must read the module you import. Reading means the module has a
requiresdirective for it, directly or throughrequires transitivefrom another module it reads. Every named module readsjava.baseimplicitly.
For example, this module-info.java lets classes in com.example.app use import module java.sql;:
module com.example.app {
requires java.sql;
}If you remove the requires java.sql; line, import module java.sql; fails to compile in that module. This keeps module imports consistent with the module system's rule that code can only use modules it declares a dependency on.
Name clashes
Importing many packages at once raises the chance that two of them contain a type with the same simple name. The rule is the same as for on-demand imports. The clash is not an error when you import. It is an error only when you use the ambiguous simple name.
java.base exports java.util.Date, and java.sql exports java.sql.Date. Importing both modules is fine until you write Date:
import module java.base;
import module java.sql;
public class AmbiguousDate {
public static void main(String[] args) {
// Date d = null; // compile error: Date is ambiguous (java.util.Date and java.sql.Date)
java.util.Date utilDate = new java.util.Date();
java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());
System.out.println(sqlDate);
}
}The commented-out line would produce an error that names both candidates. Using fully qualified names fixes it, as the rest of the class does. A shorter fix is a single-type import, which takes precedence over module imports:
import module java.base;
import module java.sql;
import java.util.Date;
public class ResolvedDate {
public static void main(String[] args) {
Date now = new Date();
System.out.println(now.getTime() > 0);
}
}Here Date means java.util.Date. The program prints true. A later chapter on shadowing and precedence covers the full rules, including how same-package types and on-demand imports compare. For now, remember that a single-type import is the tool for settling one specific name.
Compiling and running
The feature went through two preview rounds before it became final.
| JDK | Status | JEP |
|---|---|---|
| 23 | First preview | 476 |
| 24 | Second preview | 494 |
| 25 | Final, no flags needed | 511 |
On JDK 25 and later you compile and run as usual, with only a --release value if you want one. On the preview releases you must pass --enable-preview to both javac and java, and --release must match the JDK version you are using:
# JDK 25 and later (feature is final)
javac --release 25 ModuleImportDemo.java
java ModuleImportDemo
# JDK 23 (first preview)
javac --release 23 --enable-preview ModuleImportDemo.java
java --enable-preview ModuleImportDemoSome points about preview compilation:
- A class file compiled with
--enable-previewis marked as depending on preview features. It runs only on the same JDK feature release, and only with--enable-preview. - Using
import moduleon a JDK where it is a preview feature, without the flag, produces a compile error that says the feature is a preview feature and is disabled by default. - Source-launch mode also works.
java --enable-preview --source 23 ModuleImportDemo.javacompiles in memory and runs. On JDK 25 you can simply runjava ModuleImportDemo.java.
Relation to compact source files
JDK 25 also finalizes compact source files and instance main methods (JEP 512). In a compact source file, the compiler automatically behaves as if import module java.base; were present. That is why a short beginner program can use List or Math without any imports. A normal class does not get this implicit import. If you want the effect there, you write the line yourself. A later chapter covers this in more detail.
Common mistakes
- Writing a wildcard.
import module java.*;is invalid. Name a single module exactly. - Confusing module and package names.
import module java.util;fails becausejava.utilis a package, not a module. Module names are things likejava.base,java.sqlandjava.logging. - Forgetting
requiresin a named module. The error appears on the import line, not where you use a type. - Expecting non-exported types. Types in packages like
sun.miscorjdk.internal.*are not exported, so a module import never makes them visible. - Forgetting the preview flag on JDK 23 or 24. Both
javacandjavaneed--enable-preview.
Exercise
A file starts with import module java.base; and import module java.logging;. It uses Logger (from java.util.logging) and List. The code compiles. You then add import module java.desktop; and the compiler reports an error on the line that declares List<String> names = ..., though that line was not changed. What happened, and what is the smallest fix?
Show answer
java.desktop exports java.awt, which contains java.awt.List. Now the simple name List can mean java.util.List or java.awt.List, so it is ambiguous wherever it is used. The smallest fix is a single-type import, import java.util.List;, which takes precedence over module imports. Using the fully qualified name java.util.List at each use also works.
Exercise
A named module com.example.tools has a module-info.java containing only module com.example.tools { }. A class in it has import module java.net.http; and fails to compile. Why, and how do you fix it?
Show answer
Code in a named module can import only modules that the module reads, and com.example.tools reads only java.base. Add requires java.net.http; to module-info.java.
Exercise
You are on JDK 24 and want to run ModuleImportDemo.java from this chapter. What do you need to do differently from JDK 25?
Show answer
JDK 24 has import module as a second preview feature. Compile with javac --release 24 --enable-preview ModuleImportDemo.java and run with java --enable-preview ModuleImportDemo. On JDK 25 or later, the same source compiles and runs without any flags.