Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

The reference equality operator == evaluates to true only when the values it compares reference refer to 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 refer to distinct objects.

Code Block
bgColor#FFcccc
public class StringComparison {
  public static void main(String[] args) {
    String str1 = new String("one");
    String str2 = new String("one");
    System.out.println(str1 == str2); // prints "false"
  }

}

...

  • The cost of String.intern() grows as the number of intern strings grows. Performance should be no worse than O(n log n), but the Java Language Specification lacks a specific performance guarantee.
  • In early Java Virtual Machine (JVM) implementations, interned strings became immortal: they were exempt from garbage collection. This can be problematic when large numbers of strings are interned. More recent implementations can garbage-collect the storage occupied by interned strings that are no longer referenced. However, the Java Language Specification lacks any specification of this behavior.
  • In JVM implementations prior to Java 1.7, interned strings are allocated in the permgen storage region, which is typically much smaller than the remainder of the heap. Consequently interning large numbers of strings can lead to an out-of-memory condition. In many Java 1.7 implementations, interned strings are allocated on the heap, relieving this restriction. Once again, the details of allocation are unspecified by the Java Language Specification; consequently, implementations may vary.

...

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 must be immutable. The use of static factory methods, rather than public constructors, facilitates instance control, which ; this is a key enabling technique.

...