java.lang.correctness.no-string-eqeq.no-string-eqeq

Verifed by r2c
Community Favorite
profile photo of semgrepsemgrep
Author
60,754
Download Count*

Strings should not be compared with '=='. This is a reference comparison operator. Use '.equals()' instead.

Run Locally

Run in CI

Defintion

rules:
  - id: no-string-eqeq
    languages:
      - java
    patterns:
      - pattern-not: null == (String $Y)
      - pattern: $X == (String $Y)
    message: Strings should not be compared with '=='. This is a reference
      comparison operator. Use '.equals()' instead.
    severity: WARNING
    metadata:
      category: correctness
      technology:
        - java
      license: Commons Clause License Condition v1.0[LGPL-2.1-only]

Examples

no-string-eqeq.java

public class Example {
    public int foo(String a, int b) {
        // ruleid:no-string-eqeq
        if (a == "hello") return 1;
        // ok:no-string-eqeq
        if (b == 2) return -1;
        // ruleid:no-string-eqeq
        if ("hello" == a) return 2;
        //ok:no-string-eqeq
        if (null == "hello") return 12;
        //ok:no-string-eqeq
        if ("hello" == null) return 0;
    }
}