Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: rewrote code to clarify the need for null checks

...

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

  public static boolean isEqual(String str1, String str2) {
    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;
    }
    return System.out.println(result);  // prints false!
  }
}

Compliant Solution (Object.equals())

...

Code Block
bgColor#ccccff
public class GoodComparisonStringComparison {
  public static voidboolean main(String[] args) {
    isEqual(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);
    }
    return System.out.println(result); // prints true
  }
}

Compliant Solution (String.intern())

...

Code Block
bgColor#ccccff
public class GoodComparisonStringComparison {
  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 = System.out.println(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 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 Strings that have been interned become immortal; they cannot be garbage collected. This can be problematic when large numbers of strings are interned.

...