a
should not be compared to null
using equals
2 void method() {
3 String a = "er";
4
5 if (a.equals(null)) {6 System.out.println("Some message goes here");
7 }
8 }
Description
Tests for null should not use the equals
method. The '==' operator should be used instead.
Consider this string declaration:
String x = "foo";
Bad Practice
if (x.equals(null)) {
doSomething();
}
If x
is null in the above snippet, calling equals
on it would result in a NullPointerException
.
Recommended
if (x == null) {
doSomething();
}
Since the ==
operator directly compares references, it does not have the same problem.
References
- PMD - EqualsNull