Reputation: 23
I get a kind of following error from solarQube = " NullPointerException might be thrown as 'a' is nullable here". Below is simple code sample for the error.
The class :
class A {
int a1;
int a2;
public A () {
}
public int getA1() {
return a1;
}
public int getA2() {
return a2;
}
}
Then I have a method which use the class above as param :
public boolean testMethod(A a) {
if(a != null && a.getA1() != 1 || a.getA2() != 2) {
return true;
}
return false;
}
I got the error with a.getA2 != 2
highlighted by SonarQube. I just cannot understand the problem with those statement. The description of the bug describes by the SonarQube did not makes me any clearer. How can I fix it and can anyone please explain to me why it is an error ?
Upvotes: 0
Views: 3649
Reputation: 131556
Think to the operators precedence : &&
has higher priority than ||
.
Operators with higher precedence are evaluated before operators with relatively lower precedence.
So you have to understand this statement :
if(a != null && a.getA1() != 1 || a.getA2() != 2)
as whether it was written :
// Evaluated together // Evaluated then
if( (a != null && a.getA1() != 1) || a.getA2() != 2)
So a.getA2() != 2
doesn't have a null
check.
What you have to write to prevent NullPointerException
is grouped the evaluation of the two boolean expressions that need to.
You can do it by surrounding them by parenthesis :
if(a != null && (a.getA1() != 1 || a.getA2() != 2))
Upvotes: 6