Module import declarations
suggest changeA module import declaration imports every public top-level type from every package a module exports, all in one line:
import module java.base;
It was previewed in Java 23 and 24 (JEPs 476 and 494) and became final in Java 25 with JEP 511. It doesn't need --enable-preview, but it does need --release 25 or newer:
$ javac --release 24 Main.java
Main.java:1: error: module imports are not supported in -source 24
import module java.base;
^
(use -source 25 or higher to enable module imports)
1 error
You don't need to write your own modules to use it. Ordinary classpath code can import the JDK modules, and any other module, as long as the module is resolved (see below).
One import instead of ten
Code that uses collections, streams, files, dates and big numbers usually starts with a long list of imports, or several .* imports, one per package. With import module java.base; all of them become available:
import module java.base;
public class Main {
public static void main(String[] args) throws IOException {
List<String> words = List.of("delta", "alpha", "charlie", "bravo");
Map<Integer, List<String>> byLength = words.stream()
.sorted()
.collect(Collectors.groupingBy(String::length));
System.out.println(byLength);
Path tmp = Files.createTempFile("words", ".txt");
Files.write(tmp, words);
System.out.println(Files.readAllLines(tmp).size() + " lines");
Files.delete(tmp);
System.out.println(LocalDate.of(2025, 9, 16).getDayOfWeek());
System.out.println(new BigDecimal("0.1").add(new BigDecimal("0.2")));
var counter = new AtomicInteger();
System.out.println(counter.incrementAndGet());
}
}
$ javac Main.java
$ java Main
{5=[alpha, bravo, delta], 7=[charlie]}
4 lines
TUESDAY
0.3
1
IOException and Files come from java.io and java.nio.file, List and Map from java.util, Collectors from java.util.stream, LocalDate from java.time, BigDecimal from java.math and AtomicInteger from java.util.concurrent.atomic. The single import replaces seven package imports.
The syntax is import module followed by a module name. module is a contextual keyword, so packages and variables called module still work: import module.Helper; is an ordinary single-type import from a package named module.
What exactly gets imported
import module M; is the same as an on-demand import (import p.*;) of:
- every package that
Mexports without qualification (exports p;, notexports p to other.module;) - every package exported by modules that
Mreads throughrequires transitive, applied recursively
Use java --describe-module to see what that is for a given module:
$ java --describe-module java.sql
java.sql@25.0.4.1
exports java.sql
exports javax.sql
requires java.xml transitive
requires java.logging transitive
requires java.transaction.xa transitive
requires java.base mandated
uses java.sql.Driver
So import module java.sql; brings in java.sql and javax.sql, plus everything exported by java.xml, java.logging and java.transaction.xa:
import module java.sql;
public class Db {
public static void main(String[] args) {
// java.sql and javax.sql: exported by java.sql itself
System.out.println(Connection.class.getModule());
System.out.println(DataSource.class.getModule());
// java.util.logging: java.sql "requires transitive java.logging"
System.out.println(Logger.class.getModule());
// javax.xml.parsers: java.sql "requires transitive java.xml"
System.out.println(DocumentBuilderFactory.class.getModule());
// javax.transaction.xa: "requires transitive java.transaction.xa"
System.out.println(XAResource.class.getModule());
}
}
module java.sql
module java.sql
module java.logging
module java.xml
module java.transaction.xa
Note that java.sql requires java.base as mandated, not transitive. Importing java.sql does not import java.base:
import module java.sql;
public class Db2 {
public static void main(String[] args) {
List<String> l = List.of();
}
}
Db2.java:5: error: cannot find symbol
List<String> l = List.of();
^
symbol: class List
location: class Db2
Add import module java.base; as a second line. The aggregator module java.se is different: it exports no packages of its own but requires transitive all Java SE modules, including java.base, so import module java.se; imports the whole Java SE API (see below for a catch).
A few more rules:
- Packages aren't hierarchical.
java.util.concurrent.atomicis imported becausejava.baseexports it, not because it's underjava.util. Packages the module doesn't export, such asjdk.internal.miscinjava.baseorcom.example.shapes.internalin the example below, aren't imported. - Only top-level types are imported, just as with
import java.util.*;. Nested types still need their outer class: writeMap.Entry, notEntry. - Static members aren't imported.
max(1, 2)doesn't compile withimport module java.base;; you still needimport static java.lang.Math.max;orMath.max. - Importing a module twice, or importing both a module and one of its packages, is allowed and produces no warning, even with
-Xlint:all.
Resolving ambiguous names
Big modules export many packages, so two of them can contain types with the same simple name. Importing them isn't an error. Using the ambiguous name is:
import module java.base;
import module java.sql;
public class Dates {
public static void main(String[] args) {
Date d = new Date(0);
}
}
Dates.java:6: error: reference to Date is ambiguous
Date d = new Date(0);
^
both class java.util.Date in java.util and class java.sql.Date in java.sql match
It isn't always the obvious pair. java.base also exports java.security, which has its own Timestamp:
Dates.java:11: error: reference to Timestamp is ambiguous
List<Timestamp> ts = List.of(new Timestamp(0));
^
both class java.sql.Timestamp in java.sql and class java.security.Timestamp in java.security match
Fix it with a single-type import. Single-type imports shadow everything imported on demand, and the other type is still reachable by its fully qualified name:
import module java.base;
import module java.sql;
import java.sql.Date;
import java.sql.Timestamp;
public class Dates {
public static void main(String[] args) {
Date d = Date.valueOf("2025-09-16");
java.util.Date now = new java.util.Date(0);
System.out.println(d + " " + d.getClass().getName());
System.out.println(now.getClass().getName());
List<Timestamp> ts = List.of(new Timestamp(0));
System.out.println(ts.get(0).getClass().getName());
}
}
2025-09-16 java.sql.Date
java.util.Date
java.sql.Timestamp
A package on-demand import also wins over a module import. This rule was added in the second preview (Java 24); in the first preview the two kinds of import had equal priority:
import module java.base;
import module java.sql;
import java.sql.*;
public class Dates2 {
public static void main(String[] args) {
Date d = new Date(0);
System.out.println(d.getClass().getName());
}
}
java.sql.Date
So the priority, from strongest to weakest, is:
- single-type imports (
import java.sql.Date;) and types declared in the same file or package - package on-demand imports (
import java.sql.*;) - module imports (
import module java.sql;) and the implicitimport module java.base;of compact source files - the implicit
import java.lang.*;
The classic clash is List: java.desktop exports java.awt with its java.awt.List component, and java.base has java.util.List. Any Swing or AWT code that imports both modules needs import java.util.List;:
Awt.java:6: error: reference to List is ambiguous
List<String> names = List.of("a", "b");
^
both interface java.util.List in java.util and class java.awt.List in java.awt match
Because ambiguity only shows up when a name is used, upgrading a library can break your code: if a new version of a module exports a package with a type whose name you already use from another module, the next compile fails. Single-type imports for the names you depend on protect against that, which is one reason to keep module imports for small programs, prototypes and teaching code.
Importing your own modules
Module imports work with any module, not only the JDK's. Here is a library module that exports two packages and keeps a third one internal:
// shapes/module-info.java
module com.example.shapes {
exports com.example.shapes;
exports com.example.shapes.io;
// com.example.shapes.internal is not exported
}
// shapes/com/example/shapes/Shape.java
package com.example.shapes;
public sealed interface Shape permits Circle, Square {
double area();
}
// shapes/com/example/shapes/Circle.java
package com.example.shapes;
public record Circle(double r) implements Shape {
public double area() { return Math.PI * r * r; }
}
// shapes/com/example/shapes/Square.java
package com.example.shapes;
public record Square(double side) implements Shape {
public double area() { return side * side; }
}
// shapes/com/example/shapes/io/ShapeFormat.java
package com.example.shapes.io;
import com.example.shapes.Shape;
public class ShapeFormat {
public static String format(Shape s) {
return "%s, area %.2f".formatted(s, s.area());
}
}
The com.example.shapes.internal package has a Cache class. An application module imports the library with one line:
// app/module-info.java
module com.example.app {
requires com.example.shapes;
}
// app/com/example/app/Main.java
package com.example.app;
import module java.base;
import module com.example.shapes;
public class Main {
public static void main(String[] args) {
List<Shape> shapes = List.of(new Circle(1), new Square(2));
for (Shape s : shapes) {
System.out.println(ShapeFormat.format(s));
}
}
}
$ javac -d mods/com.example.shapes $(find shapes -name '*.java')
$ javac -d mods/com.example.app --module-path mods $(find app -name '*.java')
$ java --module-path mods -m com.example.app/com.example.app.Main
Circle[r=1.0], area 3.14
Square[side=2.0], area 4.00
Shape, Circle and Square come from com.example.shapes, ShapeFormat from com.example.shapes.io. Cache isn't imported because its package isn't exported.
An import doesn't replace requires. The importing module must read the imported module. Without the requires line you get:
app\com\example\app\Main.java:4: error: module com.example.app does not read: com.example.shapes
import module com.example.shapes;
^
1 error
requires transitive counts too: a module that requires java.sql can import module java.xml;. A module can also import itself, which is handy when its packages use each other a lot: a class in com.example.tool.b can write import module com.example.tool; to see the exported types of com.example.tool.a. For module-info.java basics see Defining a basic module and Modules.
Using module imports from classpath code
Code without a module-info.java lives in the unnamed module. It can import any module that is part of the module graph. All JDK modules that export an API, such as java.sql, java.net.http or java.desktop, are in the graph by default, so they just work.
A third-party module must be on the module path and resolved. Here is a plain class on the classpath that uses the shapes library:
import module com.example.shapes;
public class Report {
public static void main(String[] args) {
Shape s = new Circle(2);
System.out.println(ShapeFormat.format(s));
}
}
Putting the library on the classpath isn't enough, because on the classpath it isn't a module. Putting it on the module path isn't enough either, because nothing requires it:
$ javac -cp ../mods/com.example.shapes Report.java
Report.java:1: error: imported module not found: com.example.shapes
$ javac --module-path ../mods Report.java
Report.java:1: error: unnamed module does not read: com.example.shapes
Add it to the module graph with --add-modules, both when compiling and when running:
$ javac --module-path ../mods --add-modules com.example.shapes Report.java
$ java --module-path ../mods --add-modules com.example.shapes Report
Circle[r=2.0], area 12.57
The same applies to java.se. Because it exports no packages itself, it isn't a default root module for the unnamed module:
import module java.se;
import java.util.List;
public class Se {
public static void main(String[] args) {
List<Path> paths = List.of(Path.of("a.txt"));
System.out.println(paths);
System.out.println(HttpClient.class.getModule() + ", " + Connection.class.getModule()
+ ", " + JFrame.class.getModule());
}
}
$ javac Se.java
Se.java:1: error: unnamed module does not read: java.se
import module java.se;
^
1 error
$ javac --add-modules java.se Se.java
$ java Se
[a.txt]
module java.net.http, module java.sql, module java.desktop
Running works without the flag here, because the compiled class only refers to types in the real modules (java.net.http, java.sql, java.desktop). Note the import java.util.List; line: java.se includes java.desktop, so List would be ambiguous.
Compact source files and the source launcher
A compact source file (a .java file with top-level methods and no class declaration) automatically imports java.base, as described in Compact source files and instance main methods. It can import other modules explicitly. Here java.net.http supplies HttpRequest, while URI and Duration come from the implicit java.base import:
import module java.net.http;
void main() {
HttpRequest request = HttpRequest.newBuilder(URI.create("https://example.com/api/items"))
.header("Accept", "application/json")
.timeout(Duration.ofSeconds(5))
.POST(HttpRequest.BodyPublishers.ofString("{\"name\":\"pen\"}"))
.build();
IO.println(request.method() + " " + request.uri());
IO.println(request.headers().map());
IO.println(request.timeout().orElseThrow());
}
$ java Requests.java
POST https://example.com/api/items
{Accept=[application/json]}
PT5S
The source launcher (running a .java file directly with java, covered in Running source files without compiling) accepts the same flags as javac, so java --add-modules java.se Se.java and java --module-path mods --add-modules com.example.shapes Report.java work too.
JShell
In JDK 25 the default JShell startup script is a single import module java.base; instead of a list of package imports:
jshell> /list -start
s1 : import module java.base;
You can add module imports interactively, and the same ambiguity rules apply:
jshell> List.of("x")
$1 ==> [x]
jshell> import module java.desktop;
jshell> List.of("y")
| Error:
| reference to List is ambiguous
| both class java.awt.List in java.awt and interface java.util.List in java.util match
| List.of("y")
| ^--^
jshell> import java.util.List;
jshell> List.of("z")
$4 ==> [z]
jshell> new JButton("OK").getText()
$5 ==> "OK"
/imports lists module imports without the word module (for example | import java.base). The older JAVASE startup script (jshell --startup JAVASE) still imports every Java SE package one by one.
When to use module imports
Good fits:
- scripts, compact source files, JShell sessions and examples, where import lists are noise
- teaching, so beginners can use
ListorPathbefore learning about packages - code that uses a big, cohesive API, such as
import module java.desktop;for a Swing tool orimport module java.net.http;for an HTTP client
Reasons to stay with explicit imports:
- A single-type import list documents which classes a file depends on. A module import tells the reader almost nothing.
- New packages or types in an imported module can create ambiguities and break compilation. With explicit imports, library upgrades can't do that.
- Many style guides and IDE settings (Google Java Style, for example) forbid wildcard imports, and module imports are wildcard imports on a larger scale.
- The code must compile with Java versions before 25.
A reasonable middle ground in application code is import module java.base; plus single-type imports for everything else, and single-type imports for any name that clashes.
Summary
import module M;imports all public top-level types of packages exported byMand, throughrequires transitive, by the modules it depends on. It's final in Java 25 (JEP 511).- It doesn't import non-exported packages, nested types or static members. Importing
java.sqldoesn't importjava.base; importingjava.seimports everything. - Ambiguous simple names, such as
Date,TimestamporList, are compile errors only when used. Resolve them with a single-type import. Single-type imports beat package on-demand imports, which beat module imports. - In a named module, the module must read the imported module (
requires). In classpath code, the module must be resolved: JDK API modules are by default, while third-party modules andjava.seneed--add-modules. - Compact source files and JShell import
java.baseautomatically; add other modules with explicitimport modulelines.