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.
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}
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}