Versions Compared

Key

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

...

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(isEqual(str1, == str2)); // prints "false"
  }

  public static boolean isEqual(String str1, String str2) {
    boolean result;
    if (str1 == null) { 
      result = str2 == null;
    }
    else {
      result = str1 == str2;
    }
    return result; 
  }
}

Compliant Solution (Object.equals())

...

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

 public static boolean isEqual(String str1, String str2) {
    boolean result;
    if (str1 == null) {
      result = (str2 == null);
    } else {
      result = str1.equals(str2);
    }
    return result;
  }
}

Compliant Solution (String.intern())

...

Code Block
bgColor#ccccff
public class StringComparison {
  public static void main(String[] args) {
    String str1 = new String("one");
    String str2 = new String("one");

    str1 = str1.intern();
    str2 = str2.intern();

    System.out.println(str1 == str2); // prints "true"
  }
}

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

...