Overview
jshell (Java 9, JEP 222) is the JDK's read–eval–print loop. It accepts snippets —
expressions, statements, method and class declarations — without a surrounding class or
main, forward-references unresolved names, and silently swallows checked exceptions and
semicolons on expressions. It is the fastest way to answer "what does this API actually
return?" questions.
Key points
- Snippets: declarations can be redefined freely;
$1,$2… hold expression results; tab completion andShift-Tab iauto-import as you type. - /commands:
/vars,/methods,/types,/listshow state;/editopens an editor;/saveand/open file.jshpersist and replay sessions;/env -class-path lib.jaradds libraries;/resetstarts clean. - Feedback modes:
/set feedback verbose|normal|concise|silentcontrols how chatty results are —verboseis instructive when learning,concisefor quick work. - Scripting:
jshell script.jshorjshell -q - <<'EOF' … EOFruns non-interactive;--execution localruns snippets in-process (faster, shares the JVM), the default is a separate remote agent process. - With dependencies: launch as
jshell --class-path "$(mvn dependency:build-classpath …)"or via build-tool integrations to explore a project's own classes. - When it beats a test: probing an unfamiliar API's behaviour, checking formatting or date-arithmetic edge cases, demonstrating something to a colleague. The moment the answer is worth keeping, move it into a real test — jshell sessions are disposable by design.
Examples
jshell> var xs = java.util.stream.IntStream.rangeClosed(1,5).boxed().toList()
xs ==> [1, 2, 3, 4, 5]
jshell> /set feedback concise
jshell> /save exploration.jsh
Related
- The JDK, the JRE & their tools — parent catalog of the toolchain.
- java launcher — source-file mode is the next step up when a snippet becomes a script.
- Unit testing — where exploration graduates once the finding matters.