Class StringLiteralEqualityCheck

  • All Implemented Interfaces:
    Configurable, Contextualizable

    public class StringLiteralEqualityCheck
    extends AbstractCheck

    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))

    To configure the check:

     <module name="StringLiteralEquality"/>

    Examples of violations:

     String status = "pending";
     if (status == "done") {} // violation
     while (status != "done") {} // violation
     boolean flag = (status == "done"); // violation
     boolean flag = (status.equals("done")); // OK
     String name = "X";
     if (name == getName()) {}
     // OK, limitation that check cannot tell runtime type returned from method call

    Parent is

    Violation Message Keys:

    • string.literal.equality