Strings are compared with == or !=, which compare references

tx0/java:string-identityrecommendedwarningbug

What it finds

name == "admin" compares references, not characters: two strings with the same characters are often different objects, as when one was read from input or built at run time. equals compares the characters.

Both operands must be known to be strings, and not both constants: string literals and final variables initialized with one are the same object wherever they have the same characters. A comparison that is only a shortcut before equals on the same operands, as in a == b || a.equals(b), is left alone, and so are comparisons in assertions.

From the rule's source, string_identity.rs.

Example from the rule's tests
class Names {  static final String ADMIN = "admin";   boolean check(String name, String other, Object o) {    boolean r = name == "admin";tx0 reports: compares the references of two strings    r = name != other;tx0 reports: name != other compares the references    r = ADMIN == "admin";    r = name == null;    r = name == o;    r = name.isEmpty();    return r;  }   static boolean same(String a, String b) {    return a == b || a != null && a.equals(b);  }}
Highlighted lines are the ones tx0 reports, with its message under each; the other lines are left alone.

Turn it on, off or suppress it

The rule runs from the recommended tier up. To turn it on in a lower tier, give it a level in tx0.toml:

tx0.toml
[rules]
"tx0/java:string-identity" = "warning"

To keep one finding, suppress it with a reason. tx0 suppress ID --reason "..." writes the comment on the line before the code:

// tx0: ignore[tx0/java:string-identity] reason="..."

tx0 explain tx0/java:string-identity shows the same in the terminal. Found a false positive? Report it.