Module import declarations (preview)

Java 23 Course · lesson 6 of 15 · 4 min read

Import an entire module in one line instead of hunting for individual packages.

Open this lesson in the learning hub

Key points

  • import module java.base; makes every package that module exports available.
  • It targets beginners and scripts, where a wall of imports is pure friction before the first line of logic.
  • Ambiguity is an error you must resolve: if two modules export the same simple name, import it explicitly.
  • It does not weaken encapsulation - you still only see what the module actually exports.
  • Preview in 23, and finalised later in Java 25.

Example

// Java 23 preview (JEP 476) - requires --enable-preview.
//
//   import module java.base;          // List, Map, Stream, Path, ... all visible
//
//   void main() {
//       var names = List.of("ada", "bob");
//       System.out.println(names.stream().map(String::toUpperCase).toList());
//   }
//
// The Java 21 version, with the imports the feature removes:
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.nio.file.Path;
import java.time.LocalDate;

public class Main {
    public static void main(String[] args) {
        System.out.println(List.of("ada", "bob").stream()
                .map(String::toUpperCase).collect(Collectors.toList()));
        System.out.println(Map.of("k", 1));
        System.out.println(Path.of("a", "b"));
        System.out.println(LocalDate.of(2024, 9, 17));
        System.out.println("five imports above; 'import module java.base' replaces all of them");
    }
}

Module imports remove import ceremony without giving you access to anything a module keeps internal.

This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the Java 23 Course course, and every lesson in it is listed on the Java 23 Course contents page.