Sub topic 10
Compact Source Files and the Implicit java.base Import
This chapter covers the one place where Java writes an import module declaration for you. It assumes you know single-type and on-demand imports, can compile and run a Java class from the command line, and have read the earlier chapters on the import module syntax and on name ambiguity. You don't need to have used module-info.java.
What a compact source file is
A compact source file is a .java file that declares methods or fields directly at the top level, outside any class. Java 25 finalized this feature, so no flags are needed. Here is a complete program:
void main() {
IO.println("Hello from a compact source file");
}Save this as Hello.java and run java Hello.java. There is no class declaration, no public static, and no String[] args.
The compiler wraps the file's top-level members in an implicitly declared class. That class has these properties:
- It is a final, top-level class.
- It is named after the file, so
Hello.javaproduces classHello. - It lives in the unnamed package.
- It extends
Object.
Because the class sits in the unnamed package and the unnamed module, a compact source file cannot belong to a named module. You can't put a module-info.java next to it and expect the file to join that module.
A file that holds an ordinary class with an instance void main() method is not a compact source file. The compact form requires at least one top-level method or field outside a class declaration. The distinction matters for imports, as the next section shows.
The implicit import
A compact source file behaves as if its first line were this:
import module java.base;You never write it. The compiler adds it, and it has the same effect as the explicit form. Every public top-level type in a package that java.base exports is available by simple name. That covers java.util, java.util.stream, java.util.function, java.io, java.nio.file, java.time, java.math, java.net and the other packages java.base exports.
This program uses types from three packages and has no import lines:
void main() {
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(", "));
IO.println(joined);
IO.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 implicit import covers them. Running java Hello.java on the file above prints Ada, Alan, Grace and then 5.
IO needs no import for a different reason. In Java 25 it is java.lang.IO, and java.lang is always imported. It provides static methods such as IO.println, IO.print and IO.readln, which make small console programs short. A compact source file does not import these methods statically, so you must write the IO. prefix.
Ordinary classes do not get the import
The same code inside a normal class fails to compile:
public class Plain {
public static void main(String[] args) {
List<String> names = List.of("Ada", "Grace");
System.out.println(names);
}
}javac Plain.java reports cannot find symbol for List. Only java.lang is implicit in a normal class. To get the same convenience, add the declaration yourself:
import module java.base;
public class Plain {
public static void main(String[] args) {
List<String> names = List.of("Ada", "Grace");
System.out.println(names);
}
}So the compact source file gets nothing a normal file couldn't have. The compiler writes the one-line import module java.base; on your behalf, and that is the only difference.
Combining implicit and explicit imports
Explicit imports in a compact source file are added to the implicit one. They do not replace it. This is the usual way to reach beyond java.base:
import module java.sql;
void main() {
IO.println(java.sql.Types.VARCHAR);
}The file now sees every exported type of java.sql and of java.base. It also sees the types of modules that java.sql re-exports through requires transitive. Those include java.logging, java.xml and java.transaction.xa. This is the transitive behavior from the earlier chapter, and nothing is special for compact files.
The implicit import takes part in ambiguity checks just like a visible one. That produces a common surprise. In the next program, Date is exported by two packages: java.util (in java.base) and java.sql:
import module java.sql;
void main() {
Date d = null;
}This fails to compile with an ambiguity error on Date. You never wrote import module java.base;, but it is in effect. The same fixes apply as with explicit imports. You can use a fully qualified name, or add a single-type import, which takes precedence over module imports:
import module java.sql;
import java.util.Date;
void main() {
Date now = new Date();
java.sql.Date today = new java.sql.Date(now.getTime());
IO.println(today.getTime() == now.getTime());
}This prints true. The simple name Date means java.util.Date, and the java.sql version stays reachable by its full name.
Shadowing inside a compact file
The precedence rules from the earlier chapter hold here without change. From strongest to weakest:
- Types declared in the file, including nested types inside the implicit class.
- Single-type imports and single static imports.
- Types in the same package (the unnamed package here).
- On-demand imports and module imports, which are all the same strength.
The consequence is that you can declare your own List, Map or Stack type in a compact source file without any clash. Your declaration shadows the type from java.base:
record Stack(int size) { }
void main() {
Stack s = new Stack(3);
IO.println(s.size());
}This prints 3. The simple name Stack refers to your record, not java.util.Stack. This is convenient for small programs, but it can confuse readers who expect the familiar type. If you also need the library type, refer to it as java.util.Stack.
Version history and flags
The feature moved through several previews before it was finalized:
| JDK | Compact source files | Module imports |
|---|---|---|
| 21, 22 | Preview, as "unnamed classes" in 21 and "implicitly declared classes" in 22 | Not available |
| 23 | Second preview | First preview |
| 24 | Third preview | Second preview |
| 25 | Final | Final |
The commands for JDK 25 are plain:
# Source-launcher mode: compile in memory and run
java Hello.java
# Or compile and run separately
javac Hello.java
java HelloA preview JDK needs the flags for both steps:
javac --release 23 --enable-preview Hello.java
java --enable-preview HelloIn source-launcher mode, the same flags go on a single command: java --enable-preview --source 23 Hello.java.
Common errors
cannot find symbolforListin a normal class. The file is not a compact source file, so there is no implicit import. Addimport module java.base;or the specific imports.reference to Date is ambiguous. You imported a module that exports a type with the same simple name as one injava.base. Add a single-type import for the one you want, or qualify the name.- Trying to add
module-info.javato a compact file. A compact source file is always in the unnamed module. If you need a named module, write an ordinary class declaration and add the imports explicitly. In a named module you can only import modules that the enclosing module reads, and yourmodule-info.javamust sayrequiresfor them. - Using
printlnwithoutIO.. In JDK 25 the methods are not statically imported. WriteIO.println(...), orSystem.out.println(...). - A name that doesn't compile after you add your own type. Check whether your own declaration shadows a
java.basetype of the same name. Your type wins, so calls written for the library class may no longer fit.
When the implicit import helps
The implicit import suits scripts, teaching examples, quick experiments and single-file utilities. In those cases a block of imports is noise, and java.base covers most of what such programs need.
For larger code the explicit form is usually better. A compact source file can't join a named module, can't be split across packages, and has an implicit class you can't reference conveniently from other files. Once a program grows past one file, switch to ordinary classes. At that point decide whether you want import module java.base;, specific imports, or both, using the guidance from the earlier chapters.
Exercise
A compact source file Report.java contains import module java.sql; and the line Date d = new Date(0);. It fails to compile with an ambiguity error, even though the file never mentions java.util. Explain why, and show one fix that keeps Date meaning java.util.Date.
Show answer
The compact source file implicitly gets import module java.base;, so java.util.Date is visible. The explicit import module java.sql; also makes java.sql.Date visible, and a module import is no stronger than another module import, so the simple name Date is ambiguous. Add the single-type import import java.util.Date;, which takes precedence over module imports. Writing java.util.Date d = new java.util.Date(0); also works.
Exercise
The class below has a main method but no imports. Does it get the implicit java.base import? What is the smallest change that makes List.of("a") compile?
Show answer
It does not. The file is an ordinary class, not a compact source file, because it has no method or field outside a class declaration, so only java.lang is implicit. Add import module java.base; at the top (or import java.util.List;).