Why does this code can cause a NPE? Findbugs give me the hint, that this can occur and it does sometimes :-)
Any ideas?
public Integer whyAnNPE() {
return 1 == 2 ? 1 : 1 == 2 ? 1 : null;
}
Why does this code can cause a NPE? Findbugs give me the hint, that this can occur and it does sometimes :-)
Any ideas?
public Integer whyAnNPE() {
return 1 == 2 ? 1 : 1 == 2 ? 1 : null;
}
EDIT: The code in the question wasn't present when I wrote this answer.
Here's another method to make it slightly clearer:
The important point is that we have two conditional expressions here. The inner one is of type
Integer
due to the last bullet point in the determination of the type as specified in section 15.25.At that point, we've got a situation like this:
Now for the remaining conditional expression, the previous bullet point applies, and binary numeric promotion is performed. This in turn invokes unboxing as the first step - which fails.
In other words, a conditional like this:
involves potentially boxing the
int
to anInteger
, but a conditional like this:involves potentially unboxing the
Integer
toint
.Original answer
Here's a rather simpler example which is actually valid Java:
This is effectively:
Obviously the unboxing step here will go bang. Basically it's because of the implicit conversion of a null expression to
Integer
, and fromInteger
toint
via unboxing.