将空对象转换为整数

Ade*_*eel 5 java nullpointerexception

我试图理解以下代码。第2行输出null,而第3行抛出NullPointerException。我想念什么?从理论上讲,它应该起作用。

public static void main(String []args){

  1  Object[] obj = {null}; 
  2  System.out.println((Integer)obj[0]);  //Output null

  3  Integer n = obj[0] == null ? (Integer)obj[0] : 1; //NullPointerException
  4  System.out.println(n);
 }
Run Code Online (Sandbox Code Playgroud)

Era*_*ran 10

根据JLS中定义的规则,三元条件运算符的类型

null ? (Integer)obj[0] : 1;
Run Code Online (Sandbox Code Playgroud)

int,不是Integer

因此,当该表达式的结果为时(Integer)obj[0],将Integer取消装箱到int,然后得到NullPointerException

参见JLS 15.25。条件运算符?:表15.25-A。:

由于第二个操作数为Integer,第三个操作数为int,因此条件表达式类型为int