Sub topic 7
What Is Imported Automatically
This chapter assumes you know how import declarations work in ordinary Java and that you have written a compact source file with a main method, as in the earlier chapters. It covers which names a compact source file can use without any import line, where that convenience stops, and how to fix the errors that follow.
The Problem: Imports Are More Ceremony
In an ordinary class, only the java.lang package is imported for you. Using List, Path, or LocalDate means writing an import line first. For a ten-line program, the import block can be longer than the program.
Compact source files remove this step. The compiler treats a compact source file as if it began with this declaration:
import module java.base;You never write it, but it is in effect. A module import is an on-demand import. It makes every public top-level class and interface in every package that the named module exports available by simple name.
What java.base Contains
java.base is the module that holds the core platform. It exports many packages, and each one is imported separately. These are the ones you will use most:
| Package | Typical types |
|---|---|
| `java.lang` | `String`, `Math`, `Record`, `IO` |
| `java.util` | `List`, `Map`, `Set`, `Optional`, `Scanner`, `Date` |
| `java.util.function` | `Function`, `Predicate`, `Supplier` |
| `java.util.stream` | `Stream`, `Collectors`, `IntStream` |
| `java.io` | `File`, `IOException`, `BufferedReader` |
| `java.nio.file` | `Path`, `Files` |
| `java.time` | `LocalDate`, `Duration`, `Instant` |
| `java.math` | `BigDecimal`, `BigInteger` |
| `java.net` | `URI`, `URL` |
| `java.text` | `NumberFormat`, `DecimalFormat` |
A classic import java.util.*; does not cover java.util.function or java.util.stream, because on-demand imports never reach into sub-packages. A module import covers every exported package of the module, so Collectors and Function are available with no extra line.
Here is a program that uses types from five packages and has no import declarations:
void main() {
List<String> words = List.of("pear", "fig", "apple");
Map<Integer, List<String>> byLength =
words.stream().collect(Collectors.groupingBy(String::length));
IO.println(byLength);
IO.println(LocalDate.of(2025, 9, 16).plusDays(30));
IO.println(new BigDecimal("0.1").add(new BigDecimal("0.2")));
}It prints:
{3=[fig], 4=[pear], 5=[apple]}
2025-10-16
0.3List, Map, and Collectors come from java.util and java.util.stream. LocalDate comes from java.time. BigDecimal comes from java.math. All of these packages are exported by java.base.
Only Exported, Public, Top-Level Types
The implicit import has three limits.
- Exported packages only. Internal packages such as
jdk.internal.miscare not exported, so their types are never imported. - Public types only. A package-private class in an exported package is not visible.
- Top-level types only. Nested types such as
Map.Entryare not imported by their simple name.Mapis in scope, soMap.Entryworks, but a bareEntrydoes not.
void main() {
Map<String, Integer> ages = Map.of("Ada", 36);
for (Map.Entry<String, Integer> e : ages.entrySet()) {
IO.println(e.getKey() + " is " + e.getValue());
}
}Types Outside java.base
Many familiar types are not in java.base. JDBC (java.sql), the HTTP client (java.net.http), and Swing (java.desktop) each live in their own module. You can import such a type in the usual way, or import the whole module:
import module java.net.http;
void main() 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());
IO.println(response.statusCode());
}URI still comes from the implicit java.base import. HttpClient, HttpRequest, and HttpResponse come from the explicit module import. A module import also brings in the types of any module that the named module re-exports to its readers (a "transitive" requirement). For example, importing java.sql also makes java.logging and java.xml types available, because java.sql declares them as transitive.
Explicit module imports are not limited to compact source files. Any Java file can contain import module ...;. What only compact source files get is the implicit java.base import.
Name Clashes
On-demand imports can bring in two types with the same simple name. Using that name is a compile-time error. java.util.Date and java.sql.Date are the standard example. The implicit java.base import provides the first, and import module java.sql; provides the second:
import module java.sql;
void main() {
Date d = new Date(0L); // error: reference to Date is ambiguous
IO.println(d);
}The error appears only where the ambiguous name is used. Merely importing both modules is legal. To fix it, add a single-type import for the one you mean:
import module java.sql;
import java.util.Date;
void main() {
Date d = new Date(0L);
IO.println(d.getTime());
}This prints 0. A single-type import takes priority over on-demand imports, so the ambiguity is gone.
Your Own Declarations Win
A type declared in the file is more specific than any on-demand import, so it shadows the import of the same name. The record below hides java.util.Stack:
record Stack(int size) {}
void main() {
IO.println(new Stack(3));
}This prints Stack[size=3]. The compiler does not warn you, so if you later need the library Stack, you must rename your record or write java.util.Stack.
The order the compiler follows when it resolves a simple name looks like this:
Imports Disappear When You Wrap the File in a Class
The implicit java.base import belongs to compact source files only. When you wrap the members in an explicit class, as described in the chapter on growing a script into a full class, that class is an ordinary one. It gets only java.lang.
public class Words {
void main() {
List<String> names = List.of("Ada", "Grace"); // error: cannot find symbol
IO.println(names);
}
}IO still works because it is in java.lang. List does not. You can fix it in either of two ways:
import java.util.List;
public class Words {
void main() {
List<String> names = List.of("Ada", "Grace");
IO.println(names);
}
}or, to keep the old convenience:
import module java.base;
public class Words {
void main() {
List<String> names = List.of("Ada", "Grace");
IO.println(names);
}
}Both print [Ada, Grace]. The single-type import is the better choice in code that will be maintained, because a reader can see where each name comes from.
Choosing Between Module and Single-Type Imports
| Situation | Suggested import style |
|---|---|
| Small script or learning exercise | Rely on the implicit `java.base` import |
| Script that needs one type from another module | A single-type import such as `import java.sql.Connection;` |
| Script that uses many types from one non-base module | `import module java.sql;` |
| Library or long-lived application class | Explicit single-type imports |
| Two on-demand sources define the same name | Add a single-type import for the one you want |
Module imports make code shorter, but they hide where a name comes from. A newer JDK release can also add a type to an imported package. If that type has the same simple name as one from another on-demand source, your code may stop compiling. Single-type imports are immune to this.
Common Errors
cannot find symbolfor a type that is injava.base. The file is probably not a compact source file. It contains an explicit top-level class, so there is no implicit import.cannot find symbolforConnection,HttpClient, or similar. The type is outsidejava.base. Add a single-type import or the right module import.reference to X is ambiguous. Two on-demand imports supplyX. Add a single-type import.- Surprising behavior from a name you did not import. A type declared in your own file may be shadowing a library type.
Entrynot found. Nested types need their enclosing type:Map.Entry.
Exercise
A compact source file contains import module java.sql; and the line Date d = null;. The compiler reports that Date is ambiguous. Which two types clash, where does each come from, and what is the smallest change that fixes it so that Date means java.sql.Date?
Show answer
The clash is between java.util.Date, supplied by the implicit import module java.base;, and java.sql.Date, supplied by import module java.sql;. Add the single-type import import java.sql.Date;. Single-type imports take priority over on-demand imports, so the ambiguity disappears and Date means java.sql.Date.
Exercise
You copy the body of a working compact source file, which uses List, Collectors, and IO.println, into public class App { void main() { ... } } with no imports. Which of those three names stop compiling, and why?
Show answer
List and Collectors stop compiling. App is an ordinary class, so it imports only java.lang, and List (java.util) and Collectors (java.util.stream) are no longer in scope. IO lives in java.lang, so IO.println keeps working. Adding import module java.base; or the two single-type imports java.util.List and java.util.stream.Collectors fixes it.