Since Checkstyle 3.2
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="Checker"> <module name="TreeWalker"> <module name="StringLiteralEquality"/> </module> </module>
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
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