Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In jshell-11, why does a redeclared reference variable that resets to null still have a type?

When redeclaring Integer 'a' in line 33, why does jshell show the reference variable as an instance of Integer (refer to lines 38 & 39)? After the redeclaration, line 34 shows that 'a' is set to null. When 'a' is declared in line 6 but not given a value, or reset to null in line 22, 'a' is not considered an instance of Integer. I would expect that when the reference variable is redeclared, since its value is null, that it would not be an instance of a type; however, that is not the case.

01: java-lava:~ cafedude$ jshell
02: |  Welcome to JShell -- Version 11
03: |  For an introduction type: /help intro
04: 
05: jshell> Integer a;
06: a ==> null
07: |  created variable a : Integer
08: 
09: jshell> a instanceof Integer;
10: $2 ==> false
11: |  created scratch variable $2 : boolean
12: 
13: jshell> a = 1;
14: a ==> 1
15: |  assigned to a : Integer
16: 
17: jshell> a instanceof Integer;
18: $4 ==> true
19: |  created scratch variable $4 : boolean
20: 
21: jshell> a = null;
22: a ==> null
23: |  assigned to a : Integer
24: 
25: jshell> a instanceof Integer;
26: $6 ==> false
27: |  created scratch variable $6 : boolean
28: 
29: jshell> a = 1;
30: a ==> 1
31: |  assigned to a : Integer
32: 
33: jshell> Integer a;
34: a ==> null
35: |  modified variable a : Integer
36: |    update overwrote variable a : Integer
37: 
38: jshell> a instanceof Integer;
39: $9 ==> true
40: |  created scratch variable $9 : boolean
like image 349
B. Atkinson Avatar asked Oct 02 '18 15:10

B. Atkinson


2 Answers

The problem is that, though it says it is set to null, it actually isn't. See added comments in bug for more detail.

I've changed the bug title to: JShell: Redeclared variable should be reset

I'll attempt to fix in JDK 12.

The second issue is not a bug, Java does not allow instanceof operators that cannot be true -- behavior matches javac exactly.

like image 170
Robert Field Avatar answered Oct 17 '22 08:10

Robert Field


I've raised it as a bug and it's been accepted.

https://bugs.openjdk.java.net/browse/JDK-8211694

Good spot.

like image 28
muttonUp Avatar answered Oct 17 '22 06:10

muttonUp