The REPL: JShell

JShell is a Read–Eval–Print Loop shipped with the JDK. Use it whenever you want to try something out without creating a file.

jshell
jshell> 2 + 3 * 4
$1 ==> 14

jshell> var name = "World"
name ==> "World"

jshell> "Hello, " + name + "!"
$3 ==> "Hello, World!"

Semicolons are optional. Results without a variable get names like $1, which you can reuse.

Declarations work too

jshell> int square(int x) { return x * x; }
|  created method square(int)

jshell> square(12)
$5 ==> 144

jshell> record Point(int x, int y) {}
jshell> new Point(3, 4)
$7 ==> Point[x=3, y=4]

Redefining a method simply replaces it.

Commands

Command Does
/help list all commands
/vars /methods /types what you have defined
/list code so far, numbered
/edit 3 edit snippet 3
/save f.jsh /open f.jsh save / load a session
/imports the automatic imports
/reset start over
/exit quit

java.util, java.io, java.math, java.net, java.util.stream and java.util.function are imported for you:

jshell> List.of("a", "b").stream().map(String::toUpperCase).toList()
$1 ==> [A, B]

Shortcuts

  • Tab completes names: "text".to + Tab lists matching methods.
  • Shift+Tab, then v turns the expression you just typed into a variable declaration.

★ Exercises

  1. Compute how many seconds are in a year.
  2. Declare name and print a greeting with it.
  3. Define isEven(int) and test it with five values.
  4. Use Tab completion to list String methods starting with str.
  5. /save your session, /reset, then /open it again.