StringLiteralEquality

Since Checkstyle 3.2

Description

Checks that string literals are not used with == or !=. Since == will compare the object references, not the actual value of the strings, String.equals() should be used. More information can be found in this article.

Rationale: Novice Java programmers often use code like:

if (x == "something")
        

when they mean

if ("something".equals(x))
        

Examples

To configure the check:

<module name="Checker">
  <module name="TreeWalker">
    <module name="StringLiteralEquality"/>
  </module>
</module>
        

Examples of violations:

class Example1 {
  String getName(){
    return "Y";
  }
  void InvalidExample(){
    String status = "pending";
    // violation below, 'Literal Strings should be compared using equals(), not '==''
    if (status == "done") {}
    // violation below, 'Literal Strings should be compared using equals(), not '!=''
    while (status != "done") {}
    // violation below, 'Literal Strings should be compared using equals(), not '==''
    boolean flag = (status == "done");
    boolean flag1 = (status.equals("done"));
    String name = "X";
    if (name == getName()) {}
    // OK, limitation that check cannot tell runtime type returned from method call
  }
}
        

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