Incorrect string equality operator Medium

Use equals(), not ==, when checking if two strings are equal. This ensures strings that have the same value are treated as equal. For example, when comparing a string variable against a constant.

Detector ID
java/string-equality-check@v1.0
Category
Common Weakness Enumeration (CWE) external icon

Noncompliant example

1public void stringEqualityCheckNoncompliant(String string1, String string2) {
2    // Noncompliant: the == operator doesn't compare the contents of the strings.
3    if(string1 == string2) {
4        System.out.println("The strings are equal.");
5    }
6}

Compliant example

1public void stringEqualityCheckCompliant(String string1, String string2) {
2    // Compliant: the equals() method compares the contents of the strings.
3    if(string1.equals(string2)) {
4        System.out.println("The strings are equal.");
5    }
6}