JShell guide - intro

created onJanuary 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.

starting, basic usage and stopping

Run jshell in bash or another terminal:

jshell | Welcome to JShell -- Version 11.0.2 | For an introduction type: /help intro jshell>

jshell accepts two forms of input:

  • jshell commands
  • Java code, called snippets

Commands are distinguished from snippets by a preceding slash, i.e. or

Use to exit from jshell:

jshell> /exit | Goodbye

commands and online help

Commands start with a slash.

available commands

The command lists all available commands:

jshell> /help | Type a Java language expression, statement, or declaration. | Or type one of the following commands: | /list [<name or id>|-all|-start] | list the source you have typed | /edit <name or id> | edit a source entry ... remainder omitted ...

Well, almost all available commands. There is one command named defined in

github.com, FauxFaux / jdk9-langtools, JShellTool.java, line 1098 to 1101:

registerCommand(new Command("/debug", arg -> cmdDebug(arg), EMPTY_COMPLETION_PROVIDER, CommandKind.HIDDEN));

does what one would expect from a command named , namely switching on debugging. The parameters of can be listed with

online help for commands

To see the online help for a specific command, type , followed by the command. The preceding slash can be omitted for the command:

jshell> /help var | | /vars | ===== | | List the type, name, and value of variables that were entered. | | /vars | List the type, name, and value of the current active variables | | /vars <name> | List variables with the specified name (preference for active variables) ... remainder omitted ...

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.