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
rgettman
source share