Reputation: 16638
I was reading jls §5.1.7 and it says that there are 9 types of boxing, 9th one being Boxing From the null type to the null type
Then I read that Unboxing Conversion of null
throws a NullPointerException
. Ok that is obvious. Then why boxing of null
does not throws a NullPointerException
and what is the use of boxing null
value?
Upvotes: 1
Views: 882
Reputation: 1697
I think the doc you provide give the answer. "This rule is necessary because the conditional operator applies boxing conversion to the types of its operands, and uses the result in further calculations."
If one of second and third operands of ?:
is not boolean or numeric expressions, then boxing may be used. For example, the type of true?1:2
is int
, while the type of true?null:1
is Integer
. In the second example, auto-boxing is employed. And in the run time, the second example's type will be null type because when boxing null type, a null type will be got.
Upvotes: 0
Reputation: 1414
Converting null
to Integer does not throw NullPointerException
because null
is a valid value for any reference, e.g:
Integer intObject = null; // fine
However, you cannot do this:
int intPrimitive = intObject; // not fine
Because when you try to convert an Integer
to int
the Integer.intValue()
is called behind the scenes, but calling any method on a null reference throws NPE:
Object whatever = null;
whatever.anyMethod(); // always throws NPE
Because the reference points to null
, not an actual object of the chosen type.
Upvotes: 1