Sub topic 2
Evaluating expressions and scratch variables
This chapter assumes you have a JDK 9 or later with jshell on your PATH, and that you know basic Java expressions and types. It builds on starting and exiting a session. After reading it, you will know when JShell creates a scratch variable, how the variable gets its name and type, and which inputs create none.
What an expression is in JShell
In a compiled Java program, an expression such as 6 * 7 is not a complete statement. It must sit inside a method, inside a class. JShell accepts the bare expression, evaluates it, and prints the result.
jshell> 6 * 7
$1 ==> 42
jshell> $1 + 8
$2 ==> 50The output has three parts:
$1is the name of the variable JShell created.==>separates the name from the value.42is the value, printed in a readable form.
You did not declare $1. JShell created it because the expression had a value but you gave it no variable to hold it. These automatic variables are called scratch variables. You can use them in later input like any other variable, as $1 + 8 does above.
How the name is chosen
The number in a scratch variable's name is the ID of the snippet that created it. A snippet is one complete piece of input, and JShell numbers snippets in order from 1. The number is not a count of scratch variables. It counts every snippet in the session, including declarations, statements, imports, and even input that fails.
jshell> int x = 5
x ==> 5
jshell> x * 2
$2 ==> 10The declaration int x = 5 was snippet 1, so the next expression is $2. The spine's earlier example shows the same effect: after declaring String greeting = "Hello", the call greeting.toUpperCase() produces $2.
You can see the IDs with /list. A later chapter covers slash commands in detail, but you need /vars here to see what exists:
jshell> /vars
| int x = 5
| int $2 = 10Each entry shows the type JShell inferred, the name, and the current value.
The type of a scratch variable
JShell gives the scratch variable the static type of the expression, as if you had written the type yourself. /vars confirms this.
jshell> "abc".length()
$1 ==> 3
jshell> 10 / 4
$2 ==> 2
jshell> 10 / 4.0
$3 ==> 2.5
jshell> 'a' + 1
$4 ==> 98
jshell> Integer.MAX_VALUE + 1
$5 ==> -2147483648
jshell> /vars
| int $1 = 3
| int $2 = 2
| double $3 = 2.5
| int $4 = 98
| int $5 = -2147483648These results follow normal Java rules. Integer division truncates, char plus int is an int, and int arithmetic overflows silently. JShell does not apply any special numeric handling. If you expect a double and see a whole number, check the types of your operands.
Objects print by their toString() form. Strings are shown with surrounding quotes, which helps you tell the string "42" from the number 42.
jshell> "Ja" + "va"
$6 ==> "Java"
jshell> List.of(1, 2, 3)
$7 ==> [1, 2, 3]A scratch variable holds a value, not a formula
A scratch variable stores the result computed at the moment you entered the snippet. It does not recompute when the variables it used change.
jshell> int x = 5
x ==> 5
jshell> x * 2
$2 ==> 10
jshell> x = 7
x ==> 7
jshell> $2
$2 ==> 10After x changes to 7, $2 is still 10. If you want a value that follows x, write the expression again.
Scratch variables are ordinary variables, so you can assign to them or drop them. Assigning a new value of the same type works as usual:
jshell> $2 = 99
$2 ==> 99The /drop $2 command removes one. The next chapters cover naming your own variables, which is usually better once a value matters to you.
Which inputs do not create a scratch variable
Not every input produces a scratch variable. The rule is that JShell creates one only when the input is an expression that has a value and is not already a simple reference to a variable.
| Input | Result | Scratch variable? |
|---|---|---|
| `6 * 7` | `$1 ==> 42` | Yes |
| `"hi".toUpperCase()` | `$2 ==> "HI"` | Yes |
| `x` (an existing variable) | `x ==> 5` | No, it shows the existing variable |
| `x = 7` (an assignment) | `x ==> 7` | No, it assigns to `x` |
| `System.out.println("hi")` | prints `hi` | No, the method returns `void` |
| `int y = 3` (a declaration) | `y ==> 3` | No, it creates `y` |
Two of these cases surprise people. First, typing a variable name by itself shows its value but does not copy it into a new variable. Second, a void method call has no value, so there is nothing to store. The printed text comes from the method's own output, not from JShell's ==> feedback.
A method that returns a value you did not care about still creates a scratch variable:
jshell> List<String> names = new ArrayList<>()
names ==> []
jshell> names.add("Ada")
$2 ==> true
jshell> names
names ==> [Ada]add returns a boolean, so JShell stores true as $2. The list was still modified. A scratch variable holding a return value is a side effect of how JShell displays results, not a sign of an error.
Deciding what JShell does with your input
Failed input still uses an ID
If an expression throws an exception, JShell prints the exception and creates no variable. The snippet still received an ID, so the numbering skips ahead. The session stays open and keeps all earlier state.
jshell> Integer.parseInt("abc")
| Exception java.lang.NumberFormatException: For input string: "abc"
| (stack trace lines follow)
jshell> 1 + 1
$2 ==> 2The failed call was snippet 1, so the next result is $2, not $1. Do not assume scratch variable numbers are consecutive. Read the name that JShell prints before you reuse it.
Common mistakes
- Guessing the number. After declarations, imports, or errors, the next scratch variable is not
$1. Check the output or run/vars. - Expecting live updates. A scratch variable keeps the value it had when created. See the
xand$2example above. - Expecting a result from
void. Calls such asSystem.out.printlngive you output but no variable. - Losing a value to a later snippet. If you want a result to last, assign it to a named variable right away, for example
int total = $3. - Misreading integer results.
10 / 4is2. The type comes from the operands.
Exercise
A new JShell session runs these inputs in order: int a = 4, a * a, a, Integer.parseInt("x"), a + 1. Which scratch variables exist at the end, and what are their names and values?
Show answer
Two exist. a * a is snippet 2, so it creates $2 with value 16. a is snippet 3 and only shows the existing variable, so no scratch variable. Integer.parseInt("x") is snippet 4, throws NumberFormatException, and creates nothing. a + 1 is snippet 5, so it creates $5 with value 5.
Exercise
In a session, int n = 10 is entered, then n / 4, then n = 20. What is the value of the scratch variable after the last input, and why?
Show answer
The scratch variable is $2 with value 2, because 10 / 4 is integer division. Assigning n = 20 afterward does not change it, because a scratch variable stores the value computed when the snippet ran.