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

Compare with Current View Page History

« Previous Version 46 Next »

Java defines equality operators == and != for objects. 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.

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.

public class BadComparison {
  public static void main(String[] args) {
    String one = new String("one");
    String two = new String("one");
    if(one == two)
      System.out.println("Equal"); //not printed
  }
}

Compliant Solution (Object.equals())

To be compliant, use 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 == 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.

When a task requires both keeping only one copy of each string in memory as well as performing quick repeated string comparisons, the following 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.

General Rule

Assume that object comparisons require use of Object.equals() unless the defining classes specifically document their compliance with the exception below. See also guideline MET13-J. Ensure that hashCode() is overridden when equals() is overridden.

Exceptions

EXP01-EX1: Use of reference 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.

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
[[MITRE 2009]] CWE ID 595 "Incorrect Syntactic Object Comparison", CWE ID 597 "Use of Wrong Operator in String Comparison"


      04. Expressions (EXP)      EXP02-J. Do not use the equals method to compare the contents of arrays

  • No labels