Since Checkstyle 5.0
equals() comparison.
Also checks for String literals assigned to some field
(such as someString.equals(anotherString = "text")).
Rationale: Calling the equals()
method on String literals will avoid a potential
NullPointerException. Also, it is pretty common to see null
checks right before equals comparisons but following this rule such checks
are not required.
| name | description | type | default value | since |
|---|---|---|---|---|
| ignoreEqualsIgnoreCase | Control whether to ignore String.equalsIgnoreCase(String) invocations. |
boolean | false |
5.4 |
To configure the check:
<module name="Checker">
<module name="TreeWalker">
<module name="EqualsAvoidNull"/>
</module>
</module>
Example:
public class Example1 {
public void foo() {
String nullString = null;
// violation below 'String literal expressions should be on the left side'
nullString.equals("My_Sweet_String");
"My_Sweet_String".equals(nullString);
// violation below 'String literal expressions should be on the left side'
nullString.equalsIgnoreCase("My_Sweet_String");
"My_Sweet_String".equalsIgnoreCase(nullString);
}
}
To configure the check to allow ignoreEqualsIgnoreCase:
<module name="Checker">
<module name="TreeWalker">
<module name="EqualsAvoidNull">
<property name="ignoreEqualsIgnoreCase" value="true"/>
</module>
</module>
</module>
Example:
public class Example2 {
public void foo() {
String nullString = null;
// violation below 'String literal expressions should be on the left side'
nullString.equals("My_Sweet_String");
"My_Sweet_String".equals(nullString);
nullString.equalsIgnoreCase("My_Sweet_String");
"My_Sweet_String".equalsIgnoreCase(nullString);
}
}
All messages can be customized if the default message doesn't suit you. Please see the documentation to learn how to.
com.puppycrawl.tools.checkstyle.checks.coding