Reputation: 18712
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
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
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