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

北战南征 提交于 2019-12-05 14:15:27

问题


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

回答1:


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.




回答2:


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

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

Good spot.



来源:https://stackoverflow.com/questions/52611547/in-jshell-11-why-does-a-redeclared-reference-variable-that-resets-to-null-still

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!