Java defines the equality operators ==
and !=
for testing reference equality, but uses the Object.equals()
method and its children for testing abstract object equality. Naive programmers often confuse the intent of the ==
operation with that of the Object.equals()
method. This confusion is frequently seen in the context of String
processing.
As a general rule (subject to the exceptions below), use the Object.equals()
method to check whether two objects are abstractly equal to each other. Reserve use of the equality operators ==
and !=
for testing whether two references specifically refer to the same object (this is reference equality). See also guideline MET13-J. Ensure that hashCode() is overridden when equals() is overridden.
When operating on numeric boxed types (e.g.,Byte
, Character
, Short
, Integer
, Long
, Float
, and Double
), the numeric relational operators (e.g., <
, <=
, >
, and >=
) produce results that match those provided for arguments of the equivalent primitive numeric types. Specifically, the JLS requires auto-unboxing in this case, which results in comparison of the numeric values contained in the boxed objects (see JLS Section 5.6.2, "Binary Numeric Promotion"). But when both arguments of an equality operator (e.g., ==
or !=
) are of a numeric boxed type, the operation is a reference comparison rather than the anticipated numeric comparison, which may produce unexpected results (see EXP03-J. Avoid the equal and not equal operators when comparing values of boxed primitives).
Noncompliant Code Example
The reference equality operator ==
evaluates to true
only when the values it compares reference the same underlying object. This noncompliant example declares two distinct String
objects that contain the same value. The references, however, compare as unequal because they reference distinct objects.
public class ExampleComparison { public static void main(String[] args) { String one = new String("one"); String two = new String("one"); boolean result; // test below is redundant in this case, but required for full generality if (one == null) { result = two == null; } else { result = one == two; } System.out.println(result); // prints false } }
Compliant Solution (Object.equals())
This compliant solution uses the Object.equals()
method when comparing string values.
public class GoodComparison { public static void main(String[] args) { String one = new String("one"); String two = new String("one"); boolean result; if (one == null) { result = two == null; } else { result = one.equals(two); } System.out.println(result); } }
Compliant Solution (String.intern())
Reference equality produces the desired result when comparing string literals (for example, String one = "one";
and String two = "two";
) or when the intern
method has been used on both strings.
When a task requires both keeping only one copy of each string in memory as well as performing quick repeated string comparisons, this compliant solution may be used.
public class GoodComparison { public static void main(String[] args) { String one = new String("one"); String two = new String("one"); boolean result; if (one != null){ one = one.intern(); } if (two != null){ two = two.intern(); } result = one == two; System.out.println(result); } }
Use this approach with care; performance and clarity may be better served by use of code that applies the Object.equals()
approach and lacks a dependence on reference equality.
Exceptions
EXP01-EX1: Use of reference equality in place of object equality is permitted only when the defining classes guarantee the existence of at most one object instance for each possible object value. This generally requires that instances of such classes are immutable. The use of static factory methods rather than public constructors facilitates instance control; this is a key enabling technique.
Objects that are instances of classes that provide this guarantee obey the invariant that, for any two references a
and b
, a.equals(b)
is exactly equivalent to a == b
[[Bloch 2008]]. The String
class does not meet these requirements and consequently does not obey this invariant.
EXP01-EX2: Use reference equality to determine whether two references point to the same object instance.
Risk Assessment
Using reference equality to compare objects may lead to unexpected results.
Guideline |
Severity |
Likelihood |
Remediation Cost |
Priority |
Level |
---|---|---|---|---|---|
EXP01-J |
low |
probable |
medium |
P4 |
L3 |
Automated Detection
The Coverity Prevent Version 5.0 BAD_EQ checker can detect the instance where The "==" operator is being used for equality of objects when in ideal case equal method should have been used. The "==" operator may consider objects different when the equals method considers them the same.
Findbugs checks this guideline for type String
.
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this guideline on the CERT website.
Bibliography
[[FindBugs 2008]] ES: Comparison of String objects using == or !=
[[JLS 2005]] Section 3.10.5, "String Literals" and Section 5.6.2, "Binary Numeric Promotion"
[[MITRE 2009]] CWE ID 595 "Incorrect Syntactic Object Comparison", CWE ID 597 "Use of Wrong Operator in String Comparison"
04. Expressions (EXP) EXP02-J. Use the two-argument Arrays.equals() method to compare the contents of arrays