Java == String Equality

A common bug in Java is performing the comparison of two Strings using the == operator. As Stringsare a reference type in Java, by using the == operator this checks whether the addresses of the two objects are the same. However in majority of scenarios, the programmer intended to validate whether the contents of the two Strings are identical. As such, the equals() method must be used to validate equality.

jshell> String a = "test";
a ==> "test"

jshell> String b = "test2";
b ==> "test2"

jshell> a == b;
$7 ==> false

This can lead to various bugs in the code and as such, a Semgrep pattern can be written to detect this:

rules:
  - id: use-string-equals
    message: In Java, do not use == with strings. Use String.equals() instead.
    pattern-either:
      - pattern: if ($X == "...") ...
      - pattern: if ("..." == $X) ...

Last updated