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;
}
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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
Integerdue 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
intto anInteger, but a conditional like this:involves potentially unboxing the
Integertoint.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 fromIntegertointvia unboxing.