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 NPE when I run this code? It seems to be just a simple assignment n = price, where the price is zero. Do not worry about what this means, it is pointless.

+4
source share
6 answers

On line n = (n != null) ? 0L : price; n = (n != null) ? 0L : price; Do you have long and long as alternatives to your statement ?: . Java will interpret this as long and try to unpack long instead of the long field. When price is null, as in the first iteration, this creates an NPE.

+10
source

This is due to the fact that the price is unpacked in accordance with the possibility of returning 0L in the triple operator.

Try instead:

 Long n = null; for (Long price : new Long[]{null, 2L, 10L}) { n = (n != null) ? new Long(0L) : price; } 

And everything will work smoothly.

+3
source

If you look at the byte code, this will happen

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

when performing the comparison, Long.longValue is executed for each element in this array that raises your NullPointerException . The problem is that a triple expression combined with AutoBoxing hides what is really happening.

+2
source

Line

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

compiles to

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

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

+2
source

try

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

It tries to force price to a long primitive to match type 0L . This generates NPE if price null .

This expression works because it avoids implicit type coercion:

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

But, as others said in the comments, what you are doing here seems to make no sense.

0
source

Source: https://habr.com/ru/post/1369151/


All Articles