Discovering JShell in JDK 9

What is JShell?

One of the anticipated features in the upcoming release of Java 9 is JShell which is a Read-Eval-Print-Loop (REPL) interpreter.  

A REPL is an interactive shell that allows execution of single statements without the need to compile a complete program.

REPLs have emerged as powerful tools for learning and prototyping because they provide immediate feedback.

Why Use JShell?

JShell provides an environment for you to evaluate code snippets such as declarations, statements and expressions.  You can test Java code quickly as you write, which is useful when you’re trying to recall how to implement something, or exploring the new facets of the language.

If you are new to the language, you can think of it as a quicker path to “Hello World”.

JShell eliminates the need to create an entire compilation unit (main method wrapped in a class plus any necessary imports) to run one-off statements. 

Note that JShell is not a replacement for the compiler.   It's a tool that's deeply integrated into the JDK to allow the developer to rapidly test new code.

Getting Started

The early access release of JDK 9 can be downloaded from here. This article uses version 9 Build 149.

# cd /usr/java/

# wget http://www.java.net/download/java/jdk9/archive/149/binaries/jdk-9-ea+149_linux-x64_bin.tar.gz

# tar -zxvf jdk-9-ea+149_linux-x64_bin.tar.gz

# cd jdk-9/bin

# ./java -version
java version "9-ea"
Java(TM) SE Runtime Environment (build 9-ea+149)
Java HotSpot(TM) 64-Bit Server VM (build 9-ea+149, mixed mode)

# ./jshell
|Welcome to JShell -- Version 9-ea
|For an introduction type: /help intro

jshell> List<String> list = new ArrayList<String>();
list ==> []

jshell> list.add("Amir");
$5 ==> true

jshell> list.add("Arnie");
$6 ==> true

jshell> list.add("Beth");
$7 ==> true

jshell> list.add("Lucy");
$8 ==> true

jshell> list;
list ==> [Amir, Arnie, Beth, Lucy]

jshell> for (String name: list) {
 ...> System.out.println(name);
 ...> }
Amir
Arnie
Beth
Lucy

jshell> /exit
|Goodbye

JShell has a great collection of command descriptions available from the '/help' command.

Additional Information

For more details, check out this conference presentation by Oracle employee Robert Field, the architect of JShell: