简体   繁体   中英

Why am I getting a NullPointerException here?

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; 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 look at the byte code this happens

 49:    invokevirtual   #26; //Method java/lang/Long.longValue:()J
 52:    invokestatic    #20; //Method java/lang/Long.valueOf:(J)Ljava/lang/Long;

when doing the comparison the Long.longValue is being executed on each item in that array causing your NullPointerException . The problem is that the ternary expression in combination with AutoBoxing is obscuring whats really occurring.

The line

n = (n != null) ? 0L : price;   

gets compiled into

n = Long.valueOf(n == null ? price.longValue() : 0L);

The statement price.longValue() throws NullPointerException when price is null . Try replacing the array with new Long[] {1L, 2L, 3L} and see it work.

尝试

 n = (price != null) ? price : 0L;

It is trying to coerce price to a primitive long , to match the type of 0L . This generates the NPE if price is null .

This expression works, because it avoids the implicit type coercion:

n = (n != null) ? new Long( 0L ) : price ;

But as others have said in the comments, what you're doing here doesn't seem to make much sense anyway.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM