Sub topic 1
Trying Java Code Interactively with JShell
Prerequisites
Assume you have a JDK 9 or later installed, jshell on your PATH, basic Java syntax, and terminal experience. JShell is Java's read-eval-print loop (REPL). It evaluates input immediately, so you can test code without creating a class or main method.
Starting and Exiting JShell
Start a session from a terminal:
jshellJShell displays a prompt:
jshell>Enter /exit to leave the session:
jshell> /exit
| GoodbyeYou can also press Ctrl-D on many terminals. The version shown at startup depends on your installed JDK.
Evaluating Expressions and Scratch Variables
An expression produces a value. If you enter an expression without assigning it to a variable, JShell creates a temporary scratch variable such as $1:
jshell> 6 * 7
$1 ==> 42
jshell> $1 + 8
$2 ==> 50Scratch variables help you inspect intermediate results. They are session-specific and numbered by JShell. Do not rely on a particular number in reusable code, because earlier input changes the numbering.
Declaring and Redefining Variables
A declaration creates a named variable with a type and value:
jshell> String greeting = "Hello"
greeting ==> "Hello"
jshell> greeting.toUpperCase()
$3 ==> "HELLO"JShell lets you replace a declaration by entering the same name with a different type:
jshell> int greeting = 5
greeting ==> 5This differs from ordinary compiled Java, where declaring the same local variable name again in one scope is an error. Existing expressions that referred to the old declaration may need to be entered again.
How JShell Reads Input: Snippets and Optional Semicolons
JShell processes each complete unit of input as a snippet. A snippet can be an expression, declaration, statement, method, or class. Semicolons are usually optional for a single input:
jshell> int count = 3
count ==> 3
jshell> count++
$4 ==> 3Use semicolons when writing multiple statements in one snippet or when normal Java syntax requires them:
jshell> int a = 2; int b = 4; a + b
a ==> 2
b ==> 4
$5 ==> 6A common error is pressing Enter before a multi-line declaration is complete. JShell continues reading until it can recognize a complete snippet.
Exercise
What does $1 represent after entering 10 + 5 as the first expression in a fresh session?
Show answer
It is JShell's automatically created scratch variable containing the result, 15.