O'Reilly logo

Java Pocket Guide, 4th Edition by Robert Liguori, Patricia Liguori

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 20. JShell: the Java Shell

JShell, originally called Project Kulla, is an interactive command-line read-eval-print-loop (REPL) tool introduced in the Java 9 SDK. Similar in functionality to such interpreters as Python’s ipython and Haskell’s ghci, JShell allows users to evaluate and test fragments of code in real time without the trouble of creating a test project or a class housing a main function.

The code in this chapter was tested against JShell version 9-ea.

Getting Started

JShell can be launched from the menu of the NetBeans IDE (Tools→Java Platform Shell), from the Windows command line by running jshell.exe from the /bin/ directory of your JDK installation, or in POSIX environments with the jshell command.

When the environment has loaded, you will be greeted with a prompt:

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


jshell>

From here, you will be able to enter, execute, or modify code snippets, or interact with the JShell environment through its built-in commands.

Snippets

JShell operates upon units called snippets, which are code fragments entered by the user at the jshell> prompt. Each snippet must take a form defined in the JLS, as summarized in Table 20-1:

Table 20-1. Permitted snippet forms
Java Language Specification Production Example

Primary

10 / 2

Statement

if (value == null) { numWidgets = 0; }

ClassDeclaration

class Foo { }

MethodDeclaration

void sayHello () { System.out.println(“Hello”); }

FieldDeclaration ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required