created on | January 28, 2022 |
The jshell is a great tool for exploring libraries, testing new features of Java and for explorative programming in general. Java code entered at the shell prompt or provided by script files is evaluated by the jshell in a Read-Eval-Print-Loop (REPL). No need to compile your code and start a jvm with your code (this is what the jshell in effect does).
This guide covers most aspects of the jshell. I distilled it from playing around with jshell and poking around in the jshell source code. The section ‘feedback mode’ and searching through the history draw on Robert Field’s JShell Manual, which is definitely worth checking out. The link to it is in the ‘reference’ section.
Run jshell in bash or another terminal:
jshell accepts two forms of input:
Commands are distinguished from snippets by a preceding slash, i.e. or
Use to exit from jshell:
Commands start with a slash.
The command lists all available commands:
Well, almost all available commands. There is one command named defined in
github.com, FauxFaux / jdk9-langtools, JShellTool.java, line 1098 to 1101:
does what one would expect from a command named , namely switching on debugging. The parameters of can be listed with
To see the online help for a specific command, type , followed by the command. The preceding slash can be omitted for the command:
A lot of commands can be typed in their singular or plural form, i.e. the command to list all imports is , but jshell also accepts as an equivalent input. Same for or and quite a bunch of other commands.