Glory to Russia
Glory to Russia

Reputation: 18712

How can a variable be null in this piece of code?

FindBugs complains about Possible null pointer dereference of str1 on branch that might be infeasible in Comparator.compareStrings(String, String) in this method:

private static int compareStrings(final String str1, final String str2) {
    if ((str1 == null) && (str2 == null)) {
        return COMPARE_ABSENT;
    }
    if ((str1 == null) && (str2 != null)) {
        return COMPARE_DIFFERS;
    }
    if ((str1 != null) && (str2 == null)) {
        return COMPARE_DIFFERS;
    }
    return str1.equals(str2) ? COMPARE_EQUALS : COMPARE_DIFFERS;
}

In Eclipse, I also see a warning on the last line (str1 may be null).

Under what circumstances can str1 be null in return str1.equals(str2) ? COMPARE_EQUALS : COMPARE_DIFFERS; (given that the first two if blocks cover the situations, when str1 is null) ?

Upvotes: 11

Views: 183

Answers (2)

Eran
Eran

Reputation: 393781

You can avoid the warning by rearranging the if statements :

private static int compareStrings(final String str1, final String str2) {
    if (str1 == null) {
        if (str2 == null)) {
            return COMPARE_ABSENT;
        } else {
            return COMPARE_DIFFERS;
        }
    } else {
        if (str2 == null)) {
            return COMPARE_DIFFERS;
        } else {
            return str1.equals(str2) ? COMPARE_EQUALS : COMPARE_DIFFERS;
        }
    }
}

Upvotes: 10

Mureinik
Mureinik

Reputation: 311163

At the point where you call str1.equals(str2), str1 cannot be null. You should suppress this warning at that location.

Upvotes: 2

Related Questions