...
Code Block | ||
---|---|---|
| ||
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 | ||
---|---|---|
| ||
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 | ||
---|---|---|
| ||
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.
...
CWE-595, Comparison of object references instead of object contents | |
Rule 79, Use |
Bibliography
[Bloch 2008] | Item 69 |
ES: Comparison of String Objects Using | |
[JLS 2011] | §3.10.5, "String Literals" |
...