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

}

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(str1.equals( str2)); // printsPrints "true"
  }
}

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); // printsPrints "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. Examples include programs engaged in natural language processing and compiler-like tools that tokenize program input. For most other programs, performance and readability are often improved by the use of code that applies the Object.equals() approach and that lacks any dependence on reference equality.

...

MITRE CWE

CWE-595, Comparison of object references instead of object contents
CWE-597, Use of wrong operator in string comparison

[Rogue 2000]

Rule 79, Use equals(), not ==, to test for equality of objects

Bibliography

...