Create Scratch Variables in JShell in Java 9



JShell is a REPL interactive tool introduced in Java 9 to execute and evaluate simple Java programs like variable declarations, statements, expressions, and programs without using the main() method.

In this article, we will learn to create scratch variables in JShell in Java 9.

Variables in JShell

In Java 9, JShell allows for the declaration and use of variables without the need for a surrounding class or method structure. One may be able to explicitly declare the variable with a type, or else it might be declared implicitly using var for type inference.

C:\Users\User>jshell
| Welcome to JShell -- Version 9.0.4
| For an introduction type: /help intro

jshell> int var = 100
var ==> 100

Scratch Variable

In JShell, any value returned by a snippet is automatically saved into a scratch variable. These scratch variables can be represented by "$". When we do not assign the result of an expression to a variable, a scratch variable is created in JShell so that the output of the expression can be used later.

Example of Scratch Variables

In the below code snippet, six scratch variables have been created:

C:\Users\User>jshell
| Welcome to JShell -- Version 9.0.4
| For an introduction type: /help intro

jshell> 3+7
$1 ==> 10

jshell> 9-2
$2 ==> 7

jshell> 4*4
$3 ==> 16

jshell> 12/4
$4 ==> 3

jshell> 19%5
$5 ==> 4

jshell> String.valueOf($2)
$6 ==> "7"

Example of nonScratch Variable

In the below code snippet, the "nonScratch" variable has been created. It is not a scratch variable because it can't be represented with "$".

jshell> String nonScratch = "Tutorialspoint"
nonScratch ==> "Tutorialspoint"

Showing All Variables

In the below code snippet, "/vars" command can display both scratch and non-scratch variables for that particular session.

jshell> /vars
|    int $1 = 10
|    int $2 = 7
|    int $3 = 16
|    int $4 = 3
|    int $5 = 4
|    String $6 = "7"
|    String name = "Tutorialspoint"
Alshifa Hasnain
Alshifa Hasnain

Converting Code to Clarity

Updated on: 2025-06-11T17:24:31+05:30

314 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements