EqualsAvoidNull
Since Checkstyle 5.0
Description
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.
Properties
| name | description | type | default value | since |
|---|---|---|---|---|
| ignoreEqualsIgnoreCase | Control whether to ignore String.equalsIgnoreCase(String) invocations. |
boolean | false |
5.4 |
Examples
To configure the check:
<module name="Checker">
<module name="TreeWalker">
<module name="EqualsAvoidNull">
<property name="ignoreEqualsIgnoreCase" value="false"/>
</module>
</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);
}
}
Example of Usage
Violation Messages
All messages can be customized if the default message doesn't suit you. Please see the documentation to learn how to.
Fully Qualified Name
com.puppycrawl.tools.checkstyle.checks.coding.EqualsAvoidNullCheck
Use this fully qualified class name in configuration when an exact class reference is required.






