Casting Null Object into Integer

Adeel :

I am trying to understand the following code. Line number 2 outputs null while line 3 throws NullPointerException. What am I missing ? Theoretically it should work.

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);
 }
Eran :

Based on the rules defined in the JLS, the type of the ternary conditional operator

null ? (Integer)obj[0] : 1;

is int, not Integer.

Hence, when the result of this expression is (Integer)obj[0], the Integer is unboxed to int, and you get NullPointerException.

See JLS 15.25. Conditional Operator ? :, Table 15.25-A. :

Since your second operand is Integer and your third operand is int, the conditional expression type is int.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=163702&siteId=1