In the last tutorial we learned about JShell, the newly introduced feature of java 9. In this guide, we will see how to work with variables in JShell.
JShell – Scratch variable
When we do not assign the result of an expression to variable, a scratch variable is created so that the output of expression can be used later. These scratch variables are created by name of $1, $2, $3 and so on. Lets have a look at the following examples to understand it better.
jshell> 1+2 $1 ==> 3 jshell> 2+5 $2 ==> 7 jshell> System.out.println("sum of the two scratch variables is:"+($1+$2)) sum of the two scratch variables is:10 jshell> $1+$2 $4 ==> 10
Here the output of the expression 1+2 is assigned to a newly created scratch variable $1 and similarly the result of second expression is assigned to $2.
As you can see we have used the scratch variables $1 and $2 in the print statement and in another expression ($1+$2).
JShell – variables
We can also name the variables in JShell, just like we do in the actual java program.
jshell> int var = 100 var ==> 100 jshell> int num = var - 90 num ==> 10 jshell> System.out.println(num) 10 jshell> String num num ==> null jshell> System.out.println(num) null
In the above example, we have created a variable var
and assigned the value 100 to it.
In the next step, we have created another variable num
.
Note: We can also change the type of the variable, as you can see in the above example that we have changed the type of variable num
from int to String. Doing this would change the value of the variable to the default value of the changed data type, in our example we have change the num from int to String so that value of num is changed from 10 to null.
This is especially useful when you do not want to create unnecessary variables and reuse the ones which you have already created.
Leave a Reply