It’s almost always a mistake to compare two instances of java.lang.String
or boxed types like java.lang.Integer
using
reference equality ==
or !=
, because it is not comparing actual value but locations in memory.
Noncompliant Code Example
String firstName = getFirstName(); // String overrides equals
String lastName = getLastName();
if (firstName == lastName) { ... }; // Non-compliant; false even if the strings have the same value
Compliant Solution
String firstName = getFirstName();
String lastName = getLastName();
if (firstName != null && firstName.equals(lastName)) { ... };
See
- MITRE, CWE-595 - Comparison of Object References Instead of Object Contents
- MITRE, CWE-597 - Use of Wrong Operator in String Comparison
- CERT, EXP03-J. - Do not use the equality operators when comparing values of boxed
primitives
- CERT, EXP50-J. - Do not confuse abstract object equality with reference equality