jshell in a nutshell

One of the other cool features in Java 9, which was released in September 2017, is jshell. jshell is an interactive tool where you can execute and try Java code. It's a REPL.


REPL stands for Read, Eval, Print, and Loop. In the read phase you input some code; in the eval phase, you basically press enter and the code runs; in the print phase you directly see the output and result of the code; and then you can loop, because it's an iterative tool, so you can repeat yourself.

Start jshell

If you have a running JDK 9 or later, you can start jshell in your command prompt or terminal with the command jshell:

|  Welcome to JShell -- Version 9.0.4
|  For an introduction type: /help intro

Exit jshell

You can exit jshell with /exit or CTRL + D:

jshell> /exit
|  Goodbye

Evaluate expressions and statements

In jshell, you can evaluate Java expressions and statements. For example, a simple expression:

jshell> 1 + 1
$1 ==> 2

As you can see, a variable name is created $1 which you can reuse:

jshell> $1 + 2
$2 ==> 4

You can also evaluate more complex expressions, like bit shift operators:

jshell> 4 << 9
$3 ==> 2048

And evaluate statements:

jshell> System.out.println("Hello, world!")
Hello, world!

The output won't be assigned to a variable, because the method is void.


Note that you don't have to use semicolons in single line expressions and statements.

Try and catch

You don't have to use try and catch blocks in jshell:

jshell> Thread.sleep(10)

Tab completion

jshell supports tab completion. You can start typing and press tab for completions. For example:

If you type Thread.slee and press tab, jshell will complete it to Thread.sleep(.

Explore API's

You can also explore API's with jshell. For example, if you type Thread.sleep( and press tab, you can see all signatures of this method:

jshell> Thread.sleep(
$1   $2   $3   $4   $5   $6

void Thread.sleep(long millis) throws InterruptedException
void Thread.sleep(long millis, int nanos) throws InterruptedException

<press tab again to see documentation>

As you may guess, if you press tab again, you can see the javadoc:

jshell> Thread.sleep(
void Thread.sleep(long millis) throws InterruptedException
Causes the currently executing thread to sleep (temporarily cease execution) for
the specified number of milliseconds, subject to the precision and accuracy of
system timers and schedulers.The thread does not lose ownership of any monitors.

millis - the length of time to sleep in milliseconds

Thrown Exceptions:
IllegalArgumentException - if the value of millis is negative
InterruptedException - if any thread has interrupted the current thread. The
                       interrupted status of the current thread is cleared when
                       this exception is thrown.

<press tab to see next documentation>