Short form for Java If the operator returns a NullPointerException when one of the returned objects is zero

Why does this code return an error: java.lang.NullPointerException

Object obj = null; Long lNull = null; Long res = obj == null ? lNull : 10L; 

But the following method works without errors:

 Object obj = null; Long res = obj == null ? null : 10L; 
+7
java nullpointerexception null if-statement
source share
3 answers

In the second case, the compiler can conclude that null must be of type Long . In the first case, this is not so - and assumes that the expression returns a Long . You can see that this is so (e.g. fix), for example,

 Long res = obj == null ? lNull : (Long) 10L; 

which does not throw a NullPointerException.

+3
source share

The error occurs because in your case for the standard one, an unboxing value of the boxed type is required :

If one of the second and third operands has a primitive type T , and the type of the other is the result of applying the box transform (section 5.1.1) to T , then the conditional expression type is T

In your case, T is long , because 10L is long and lNull is long , that is, the result of applying the box to long conversion.

The standard further states that

If necessary, the decompression conversion is performed as a result.

This is the exception. Note that if you invert the condition, the exception will 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); 
+2
source share

JLS, section 15.25 talks about the type of expression of a conditional statement for various combinations of types of the second and third operands. There are many tables comparing two types in all relevant combinations with the type of result.

 3rd β†’ long 2nd ↓ ... Long long ... null lub(null,Long) 

In your first example, there is Long and a Long , which gives Long . This requires lNull be unpacked, which explains NullPointerException .

In your second example, there is a literal null (not a null variable) and Long . This results in "lub (null, Long)" or Long , and no decompression is performed, so no NPE is observed.

You can avoid NPE by using your first example, or cast 10L like Long , because a null and a Long give a Long .

 3rd β†’ Long 2nd ↓ ... Long Long 
0
source share

All Articles