EqualsAvoidNull

Since Checkstyle 5.0

Description

Checks that any combination of String literals is on the left side of an 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"/>
  </module>
</module>
        

Example:

String nullString = null;
nullString.equals("My_Sweet_String");            // violation
"My_Sweet_String".equals(nullString);            // OK
nullString.equalsIgnoreCase("My_Sweet_String");  // violation
"My_Sweet_String".equalsIgnoreCase(nullString);  // OK
        

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:

String nullString = null;
nullString.equals("My_Sweet_String");            // violation
"My_Sweet_String".equals(nullString);            // OK
nullString.equalsIgnoreCase("My_Sweet_String");  // OK
"My_Sweet_String".equalsIgnoreCase(nullString);  // OK
        

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.

Package

com.puppycrawl.tools.checkstyle.checks.coding

Parent Module

TreeWalker