When I write my java code like this:
Map map = new HashMap<>()
Long number =null;
if(map == null)
number = (long) 0;
else
numbe
What is happening here? Both these code paths are exactly equivalent isn't it?
They are not equivalent; the ternary operator has a few caveats.
The if-true argument of the ternary operator, (long) 0
, is of the primitive type long
. Consequently, the if-false argument will be automatically unboxed from Long
to long
(as per JLS §15.25):
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
.
However, this argument is null
(since your map does not contain the string "non-existent key"
, meaning get() returns null
), so a NullPointerException
occurs during the unboxing process.