Long n = null;
for (Long price : new Long[]{null, 2L, 10L}) {
n = (n != null) ? 0L : price;
}
I'm stumped, why am I getting a NPE when I execute this code ? Seems to be just a simple assignment of n = price where price is null. Don't worry about what it means, it makes no sense.
In the line n = (n != null) ? 0L : price;
, you have a long
and a Long
as the alternatives to your ?:
statement. Java is going to construe this as of type long
and will try to unbox the Long
, instead of box the long
. When price
is null, as it is in the first iteration, this generates an NPE.
This is because price is being unboxed to match the 0L
return possibility in the ternary operator.
Try instead:
Long n = null;
for (Long price : new Long[]{null, 2L, 10L}) {
n = (n != null) ? new Long(0L) : price;
}
And all will run smoothly.
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