Sub topic 2
Evaluating Expressions and Scratch Variables in JShell
This chapter assumes that you have a JDK 9 or later, the jshell command on your PATH, basic Java syntax, and terminal experience. An expression is Java code that produces a value, such as 6 * 7 or "hello".length().
Entering expressions
Start JShell from a terminal:
jshellAt the jshell> prompt, enter an expression without a class or main method:
jshell> 6 * 7
$1 ==> 42
jshell> "Java".toUpperCase()
$2 ==> "JAVA"
jshell> Math.max(12, 20)
$3 ==> 20JShell evaluates each complete input immediately and prints the result. The output name, such as $1, is a scratch variable. JShell creates it automatically when you do not assign the result to a variable yourself.
A scratch variable has a type inferred from the expression. In this example, $1 is an int, while $2 is a String:
jshell> $1 + 8
$4 ==> 50
jshell> $2.length()
$5 ==> 4The number increases as JShell evaluates more expressions. Do not rely on a particular number when writing reusable code. The number depends on what was entered earlier in the session.
Expressions and side effects
An expression can calculate a value or cause a side effect, such as printing text:
jshell> System.out.println("Testing")
Testing
jshell> int result = 6 * 7
result ==> 42The declaration creates the named variable result. JShell still prints the value assigned to it, but later input refers to result, not to a scratch variable:
jshell> result + 8
$6 ==> 50A semicolon is optional for many inputs. Both forms work:
jshell> 10 + 5
$7 ==> 15
jshell> 10 + 5;
$8 ==> 15The semicolon can change how JShell displays an expression. In particular, a semicolon suppresses the displayed result for some expression statements:
jshell> String message = "ready";
message ==> "ready"The declaration still happens. The semicolon does not undo the assignment.
The evaluation flow
If an expression is incomplete, JShell waits for more input. If it is invalid, JShell reports a diagnostic and keeps the session running. Earlier scratch variables remain available unless you remove them or exit JShell.
Exercise
In a new JShell session, evaluate 9 * 9, then use its scratch variable to subtract 10. What result should the second expression produce?
Show answer
The first expression creates $1 with value 81. Enter $1 - 10; the result is 71, usually shown as $2 ==> 71.