Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why am I getting a NullPointerException here?

Tags:

java

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.

like image 867
bouncyrabbit Avatar asked Dec 02 '22 01:12

bouncyrabbit


2 Answers

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.

like image 168
Sean Owen Avatar answered Dec 04 '22 13:12

Sean Owen


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.

like image 37
Kris Avatar answered Dec 04 '22 15:12

Kris