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) ?
You can assign null to a variable to denote that currently that variable does not have any value but it will have later on. A null means absence of a value. In the above example, null is assigned to a variable myVar. It means we have defined a variable but have not assigned any value yet, so value is absence.
If a reference points to null , it simply means that there is no value associated with it. Technically speaking, the memory location assigned to the reference contains the value 0 (all bits at zero), or any other value that denotes null in the given environment.
To set the value of a variable is it's equal to null , use the nullish coalescing operator, e.g. myVar = myVar ?? 'new value' . The nullish coalescing operator returns the right-hand side operand if the left-hand side evaluates to null or undefined , otherwise it returns the left-hand side operand.
'Null' in JavaScript If you wish to shred a variable off its assigned value, you can simply assign 'null' to it. Besides this, like any other object, it is never implicitly assigned to a variable by JavaScript. Upon execution, the code will print null.
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;
}
}
}
At the point where you call str1.equals(str2)
, str1
cannot be null
. You should suppress this warning at that location.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With