Why this code returns the error: java.lang.NullPointerException
Object obj = null;
Long lNull = null;
Long res = obj == null ? lNull : 10L;
But the following way works without any errors:
Object obj = null;
Long res = obj == null ? null : 10L;
In the second case, the compiler can infer that the null
must be a Long
type. In the first case, it doesn't - and assumes that the expression returns a long
. You can see that this is the case (i.e. fix it) like,
Long res = obj == null ? lNull : (Long) 10L;
which does not yield a NullPointerException.
The error happens because in your case the standard requires unboxing the value of a boxed type:
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) toT
, then the type of the conditional expression isT
.
In your case T
is long
, because 10L
is long
and lNull
is Long
, i.e. the result of applying boxing conversion to long
.
The standard further says that
If necessary, unboxing conversion is performed on the result.
This is what causes the exception. Note that if you invert the condition, the exception would no longer be thrown:
Long res = obj != null ? lNull : 10L;
You can fix the problem by explicitly asking for Long
instead of using long
, i.e.
Long res = obj == null ? lNull : Long.valueOf(10L);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With