You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 61 Next »

Java defines the equality operators == and != for testing reference equality, but uses the Object.equals() method and its subclasses 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, 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. Classes that define an equals() method must also define a hashCode() method.

This use of the equality operators also applies to numeric boxed types (for example,Byte, Character, Short, Integer, Long, Float, and Double), although the numeric relational operators (such as <, <=, >, and >=) produce results that match those provided for arguments of the equivalent primitive numeric types. See guideline EXP03-J. Avoid the equality operators when comparing values of boxed primitives for more information.

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, are unequal because they reference distinct objects.

public class ExampleComparison {
  public static void main(String[] args) {
    String str1 = new String("one");
    String str2 = new String("one");
    boolean result;
    // test for null is redundant in this case, but required for full generality
    if (str1 == null) { 
      result = str2 == null;
    }
    else {
      result = str1 == str2;
    }
    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 str1 = new String("one");
    String str2 = new String("one");
    boolean result;

    // test for null is redundant in this case, but required for full generality
    if (str1 == null) {
      result = (str2 == null);
    } else {
      result = str1.equals(str2);
    }
    System.out.println(result); // prints true
  }
}

Compliant Solution (String.intern())

Reference equality behaves like abstract object equality when comparing two strings that are each the result of the String.intern() method. This solution can be used for fast string comparisons when only one copy of each string is required.

public class GoodComparison {
  public static void main(String[] args) {
    String str1 = new String("one");
    String str2 = new String("one");
    boolean result;

    // test for null is redundant in this case, but required for full generality
    if (str1 != null) {
      str1 = str1.intern();
    }

    // test for null is redundant in this case, but required for full generality
    if (str2 != null) {
      str2 = str2.intern();
    }
    result = str1 == str2;

   System.out.println(result); // prints true
  }
}

Use of String.intern() should be reserved for cases where tokenization of strings either yields an important performance enhancement or dramatically simplifies code. The performance and readability is often improved by the use of code that applies the Object.equals() approach and lacks any dependence on reference equality.

The performance issue arises because:

  • the cost of String.intern() grows as the number of intern strings grows. Performance should be no worse than n log n, but the JLS makes no guarantee.
  • strings that have been interned become immortal; they cannot be garbage collected. This can be problematic when large numbers of strings are interned.

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.

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, ideally, the equal method should have been used. The "==" operator could 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.

Related Guidelines

MITRE CWE: CWE-595 "Incorrect Syntactic Object Comparison"

MITRE CWE: CWE-597 "Use of Wrong Operator in String Comparison"

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"


      04. Expressions (EXP)      EXP02-J. Use the two-argument Arrays.equals() method to compare the contents of arrays

  • No labels