Sub topic 6
Default imports and adding your own
Assume you have a JDK 9 or later, basic Java syntax, and a terminal. This chapter focuses on how JShell makes common classes available and how to add imports for your own code.
Imports that JShell provides
An import lets Java code use a class by its short name instead of its full package name. For example, java.util.List is the full name, while List is the short name.
JShell automatically imports several common packages, including:
java.lang.*java.io.*java.math.*java.net.*java.nio.file.*java.util.*java.util.concurrent.*java.util.function.*java.util.prefs.*java.util.regex.*java.util.stream.*
That is why List, Path, BigDecimal, and IntStream work without an explicit import.
jshell> List<String> names = List.of("Ada", "Grace")
names ==> [Ada, Grace]
jshell> IntStream.rangeClosed(1, 5).sum()
$2 ==> 15
jshell> Path file = Path.of("notes.txt")
file ==> notes.txtThe wildcard in java.util.* means “all accessible types directly in this package.” It does not include subpackages. The package java.util.concurrent, for example, needs its own default import.
Use /imports to see the imports active in the current session:
jshell> /imports
| import java.io.*
| import java.math.*
| import java.net.*
| import java.nio.file.*
| import java.util.*
| ...Adding an import
Use an ordinary Java import declaration as a JShell snippet. The import remains available for later snippets in the same session.
jshell> import java.time.LocalDate
jshell> LocalDate today = LocalDate.now()
today ==> 2026-11-26You can import one class, an entire package, or a static member:
jshell> import java.time.*
jshell> LocalDate launch = LocalDate.of(2024, 1, 1)
jshell> import static java.lang.Math.*
jshell> round(sqrt(81))
$4 ==> 9A static import makes static methods or fields available without their class name. Use it sparingly. Code such as Math.round(Math.sqrt(81)) is more explicit when the source will be shared or moved into a compiled program.
Imports are session state. They are available until you leave JShell or use /reset.
flowchart TD
A[Start JShell] --> B[Default imports available]
B --> C{Need another type?}
C -->|No| D[Use short class name]
C -->|Yes| E[Enter an import declaration]
E --> F[Use the imported type]
F --> G{Need a clean session?}
G -->|Yes| H[/reset clears session state]
G -->|No| FCommon errors
If two imported packages contain classes with the same short name, use the fully qualified name for the ambiguous class:
jshell> java.util.Date utilDate = new java.util.Date()If JShell reports that a class cannot be found, check its package name and whether that class is available on the current class path. /imports shows what is already imported, but it does not show every class available in the JDK.
Exercise
Which declaration lets you use LocalDate without writing java.time.LocalDate each time?
Show answer
Enter import java.time.LocalDate or import java.time.* before using LocalDate.