Sub topic 3
Declaring and redefining variables
This chapter assumes you can start JShell and evaluate expressions, and that you know Java's primitive and reference types. It covers how JShell creates variables, what it prints back, and what happens when you declare a name that already exists.
Declaring a variable
A variable declaration works as in ordinary Java, but it needs no class or main method. JShell evaluates the declaration and prints the name and the stored value.
jshell> int count = 3
count ==> 3
jshell> String greeting = "Hello"
greeting ==> "Hello"
jshell> double[] ratios = {0.5, 1.5}
ratios ==> double[2] { 0.5, 1.5 }The ==> arrow separates the variable name from its current value. Strings are shown with quotes and arrays show their type, length and elements, so you can tell values apart without calling toString().
You can also assign to an existing variable. JShell prints the new value the same way.
jshell> count = 10
count ==> 10
jshell> count * 2
$4 ==> 20The scratch variable is $4 because the number is the ID of the snippet that produced it, not a counter of scratch variables. This matches the earlier chapter on expressions: each input you enter gets the next ID, whether or not it creates a variable.
Declaring without an initializer
A local variable in compiled Java must be assigned before use. A JShell variable does not have this rule. If you leave out the initializer, JShell gives the variable its default value, as Java does for a field.
| Declared type | Value after `Type name;` |
|---|---|
| `int`, `long`, `short`, `byte` | `0` |
| `double`, `float` | `0.0` |
| `boolean` | `false` |
| `char` | `'\000'` |
| Any reference type, such as `String` | `null` |
jshell> int total;
total ==> 0
jshell> String label;
label ==> nullThis happens because JShell wraps each variable in a generated class as a field, and fields get defaults. It is also why the usual "variable might not have been initialized" error never appears.
Letting the compiler pick the type with var
JShell supports var, with the same rules as in Java 10 and later. The type is inferred from the initializer, and JShell prints that type in /vars.
jshell> var names = new ArrayList<String>()
names ==> []
jshell> var limit = 100L
limit ==> 100Here names has type ArrayList<String> and limit has type long. As in compiled Java, var needs an initializer, so var x; is an error.
Redeclaring a variable
In a Java source file, declaring the same name twice in one scope is a compile error. JShell allows it. A new declaration with the same name replaces the old variable, even if the type is different.
jshell> String greeting = "Hello"
greeting ==> "Hello"
jshell> int greeting = 5
greeting ==> 5
jshell> greeting + 1
$3 ==> 6The old String variable is gone and the old value is not kept. The same applies when the type is unchanged: declaring int count = 0; again resets count to 0.
This design suits experiments. You can fix a typo in a declaration by retyping it, with no need to restart the session or pick a new name.
What happens to code that uses the variable
Other snippets can refer to a variable, such as a method that reads it. When you replace the variable, JShell recompiles those dependent snippets against the new declaration.
jshell> int rate = 3
rate ==> 3
jshell> int scaled(int x) { return x * rate; }
| created method scaled(int)
jshell> scaled(5)
$3 ==> 15
jshell> rate = 4
rate ==> 4
jshell> scaled(5)
$5 ==> 20Assigning a new value updates what the method sees, because the method reads the variable at call time. Redeclaring with a different type can break dependents. If rate became a String, the expression x * rate would no longer compile, and JShell would report that scaled cannot be invoked until it is fixed. Use /methods to see which methods are affected, then redeclare them.
Modifiers and access
Top-level declarations in JShell are not class members you can protect, so keywords such as private, public, protected, static and final have no effect. JShell ignores them and prints a warning.
jshell> final int fixed = 1
| Warning:
| Modifier 'final' not permitted in top-level declarations, ignored
| final int fixed = 1;
| ^
fixed ==> 1
jshell> fixed = 2
fixed ==> 2This is a common surprise. You cannot use final to guard a value in a session, so check the variable yourself if you depend on it.
Declaration errors
If a declaration does not compile, JShell prints the compiler message and creates nothing. Any variable with the same name keeps its old value.
jshell> int size = 4
size ==> 4
jshell> int size = "four"
| Error:
| incompatible types: java.lang.String cannot be converted to int
| int size = "four";
| ^----^
jshell> size
size ==> 4The failed line is rejected in full, so the earlier size is still there. This differs from a successful redeclaration, which always overwrites.
Inspecting and removing variables
Two commands help you manage variables.
/varslists the active variables with their types and current values. Pass a name or ID, as in/vars size, to list only that one./drop namedeletes a variable. You can also pass the snippet ID, which is useful for scratch variables such as$4.
jshell> /vars
| int count = 10
| String label = null
| int size = 4
jshell> /drop label
| dropped variable labelDropping a variable that other snippets use does not delete those snippets. They become unresolved, as in the forward references section later in this tutorial, until you declare the name again.
Common mistakes
- Expecting a redeclaration to keep the value. It resets to the initializer or to the default value.
- Using
finaland assuming it protects the variable. JShell ignores it. - Reusing a scratch variable name in your own code and being surprised when the number shifts. The
$nname depends on the snippet ID, so treat it as a short-term convenience. - Forgetting that
int total;printstotal ==> 0. Do not read this as an assignment you made.
Exercise
You enter String s = "abc", then int s = 7, then s.length(). What does the third input produce, and why?
Show answer
It produces a compile error, because s is now an int and an int has no length() method. The second declaration replaced the String variable, so the earlier type is gone.
Exercise
A method int scaled(int x) { return x * rate; } uses int rate = 3. You assign rate = 4, and later redeclare String rate = "x". What happens to scaled in each case?
Show answer
After rate = 4, scaled(5) returns 20 because the method reads the current value. After String rate = "x" the expression x * rate no longer compiles, so JShell marks scaled as unusable until you redeclare it with valid code.