Sub topic 1
Starting and Exiting JShell
JShell is Java's read-eval-print loop (REPL). It lets you enter Java code, run it immediately, and see the result without first creating a source file, class, or main method. JShell is included with the JDK starting with Java 9.
Prerequisites
You should have:
- A JDK version 9 or later installed.
- The
jshellcommand available on yourPATH. - Basic knowledge of Java expressions and statements.
- A terminal or command prompt.
Check that the JDK and JShell are available:
java --version
jshell --versionThe version numbers depend on your installed JDK. A Java Runtime Environment alone might not include JShell.
Starting a session
Open a terminal and run:
jshellJShell prints a welcome message and displays the jshell> prompt:
$ jshell
| Welcome to JShell -- Version 21
| For an introduction type: /help intro
jshell>The version shown is the version installed on your computer. The prompt means JShell is waiting for input. Try a simple expression:
jshell> 6 * 7
$1 ==> 42JShell evaluates the expression and displays the result. The $1 name is an automatically created scratch variable. You can use it later in the same session:
jshell> $1 + 8
$2 ==> 50JShell keeps the session state in memory while the session is running. This state can include variables, methods, imports, and classes that you define.
Reading startup feedback
Messages beginning with | are feedback from JShell. They are not Java code. For example, the welcome text explains how to get help:
jshell> /help introA slash command is an instruction to JShell itself. It is different from Java code. For example, /help lists available commands, while 1 + 1 is a Java expression.
If you enter invalid Java code, JShell reports the problem and normally keeps the session open:
jshell> 6 *
| Error:
| illegal start of expression
| 6 *
| ^Correct the input at the next prompt. An error in one input does not usually end the entire session.
Exiting JShell
Use /exit to leave the session:
jshell> /exit
| GoodbyeYou can also send the end-of-file signal, usually by pressing Ctrl-D on macOS or Linux. On Windows, Ctrl-Z followed by Enter commonly sends the equivalent signal. /exit is explicit and works well in scripts and demonstrations.
Exiting JShell discards the current in-memory session unless you have saved the commands separately. Later chapters cover scripts for saving and replaying input.
Exercise
Which command starts JShell, and which command exits it?
Show answer
Run jshell in the terminal to start a session. Enter /exit at the jshell> prompt to end it.