The behavior you encountered results from the rules of determining the type of the ternary conditional expression.
In your case, the type of the expression
val == null ? val : val.intValue();
is int
.
This is specified by JLS 15.25. :
The type of a conditional expression is determined as follows:
If the second and third operands have the same type (which may be the null type), then that is the type of the conditional expression.
If one of the second and third operands is of primitive type T, and the type of the other is the result of applying boxing conversion (§5.1.7) to T, then the type of the conditional expression is T.
Your second operand is Integer
and your third operand is int
, therefore the type of the expression is int
.
Therefore, when val == null, val
is un-boxed (i.e. val.intValue()
is called for a null value) and a NullPointerException
is thrown.
In your if-else expression val
is not un-boxed when its value is null (since you assign it to an Object
variable, so there's no NullPointerException
.
That said, since you are assigning an Integer variable to an Object variable, your conditions in either of the snippets are pointless (since assigning an int
to an Object
variable simply boxes the int
back to Integer
).
You can simply assign
Object res = val;
and get the same end result without the exception.