Java defines the equality operators ==
and !=
for objectstesting 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, and use the equality operators ==
and !=
only to test whether two references specifically refer to the same object.
Further confusion arises because the numerical comparison operators <
, <=
, >
, and >=
can be used with the numeric boxed types Byte
, Character
, Short
, Integer
, Long
, Float
, and Double
. In this case, auto-unboxing results in the numeric values contained in the boxed objects being compared, with the expected results (see JLS Section 5.6.2, "Binary Numeric Promotion"). When both arguments of a ==
or !=
operator are numeric boxed type, the equality operators are defined to be reference equality operators; the operation is thus 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 boxed primitives).
Noncompliant Code Example
The reference equality operator ==
evaluates to true
when and 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.
Code Block | ||
---|---|---|
| ||
public class BadComparisonExampleComparison { public static void main(String[] args) { String one = new String("one"); String two = new String("one"); boolean result; if (one == null){ // test is redundant in this case, but required for full generality result = two == null; } else{ result = one == two); } System.out.println("Equal"result); //not prints printedfalse } } |
Compliant Solution (Object.equals())
To be compliant, use the Object.equals()
method when comparing string values.
Code Block | ||
---|---|---|
| ||
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 == two || one.equals(two);
}
System.out.println(result);
}
}
|
Compliant Solution (String.intern())
Reference equality produces the desired result when comparing string literals (e.g. String one = "one";
and String two = "two";
) or when the intern
method has been used on both strings.
...
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.
General Rule
Assume that object comparisons require use of Object.equals()
unless the defining classes specifically document their compliance with the exception EXPO1-EX1 below. Reserve use of the ==
and !=
operators for testing reference equality. See also guideline MET13-J. Ensure that hashCode() is overridden when equals() is overridden.
Exceptions
EXP01-EX1: Use of reference equality in place of object equality is permitted when, and 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.
...
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
Wiki Markup |
---|
\[[FindBugs 2008|AA. Bibliography#FindBugs 08]\] ES: Comparison of String objects using == or \!= \[[JLS 2005|AA. Bibliography#JLS 05]\] [Section 3.10.5|http://java.sun.com/docs/books/jls/third_edition/html/lexical.html#3.10.5], "String Literals" and [Section 5.6.2|http://java.sun.com/docs/books/jls/third_edition/html/conversions.html#5.6.2], "Binary Numeric Promotion" \[[MITRE 2009|AA. Bibliography#MITRE 09]\] [CWE ID 595|http://cwe.mitre.org/data/definitions/595.html] "Incorrect Syntactic Object Comparison", [CWE ID 597|http://cwe.mitre.org/data/definitions/597.html] "Use of Wrong Operator in String Comparison" |
...