lundi 9 juillet 2018

SonarQube Java 'NullPointerException might be thrown' in if statement

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 ?

Aucun commentaire:

Enregistrer un commentaire