Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Changed to Applicability and updated references to Java 7

...

  • The cost of String.intern() grows as the number of intern strings grows. Performance should be no worse than n log n, but the Java Language Specification lacks a specific performance guarantee.
  • Interned strings become immortal: they cannot be garbage-collected. This can be problematic when large numbers of strings are interned.

Exceptions

Applicability

Using reference equality to compare objects can lead to unexpected results.

EXP50-EX0: Using 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, which 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 fails to meet these requirements and consequently fails to preserve this invariant.

EXP50-EX1: Use reference equality to determine whether two references point to the same object.

Risk Assessment

Using reference equality to compare objects can lead to unexpected results.

Guideline

Severity

Likelihood

Remediation Cost

Priority

Level

EXP50-JG

low

probable

medium

P4

L3

Automated Detection

The Coverity Prevent Version 5.0 BAD_EQ checker can detect instances where the == operator is being used for equality of objects when, ideally, the equals() method should have been used. The == operator could consider the objects to be different, whereas the equals() method would consider them to be the same.

...

[FindBugs 2008]

ES: Comparison of String objects using == or !=

[JLS 20052011]

§3.10.5, "String Literals"

 

§5.6.2, "Binary Numeric Promotion"