Auto-unboxing need of ternary if-else
The type of the ternary conditional expression
1 <= 3 ? nullInt : -1
is int
(the JLS contains several tables that describe the type of the ternary conditional operator depending on the types of the 2nd and 3rd operands).
Therefore, when it tries to unbox nullInt
to an int
, a NullPointerException
is thrown.
In order to get the behavior of your if-else snippet, you need to write:
1 <= 3 ? nullInt : Integer.valueOf(-1)
Now the type of the expression will be Integer
, so no unboxing will take place.
I'm pretty sure that arguments to ternary operator need to be of this same type. Since you using -1 and some constant nullint
compiler tries to unbox nullint
to get value. And then autobox it to store in secondNull
variable.