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:
|WelcometoJShell--Version9-ea|Foranintroductiontype:/helpintrojshell>
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:
| Java Language Specification Production | Example |
|---|---|
Primary |
|
Statement |
|
ClassDeclaration |
|
MethodDeclaration |
|
FieldDeclaration ... |
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access