Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Short form for Java If statement returns NullPointerException when one of the returned objects is null [duplicate]

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;
like image 214
Pavel Kataykin Avatar asked Mar 22 '18 18:03

Pavel Kataykin


2 Answers

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.

like image 126
Elliott Frisch Avatar answered Sep 20 '22 20:09

Elliott Frisch


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) to T, then the type of the conditional expression is T.

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);
like image 44
Sergey Kalinichenko Avatar answered Sep 19 '22 20:09

Sergey Kalinichenko