...
Code Block | ||
---|---|---|
| ||
public class BadComparison { public static void main(String[] args) { String one = new String("one""one"); String two = new String("one""one"); if(one == two) System.out.println("Equal""Equal"); //not printed } } |
Compliant Solution
...
Code Block | ||
---|---|---|
| ||
public class GoodComparison { public static void main(String[] args) { String one = new String("one""one"); String two = new String("one""one"); boolean result; if (one == null){ result = two == null; } else{ result = one == two || one.equals(two); } System.out.println(result); } } |
...
Code Block | ||
---|---|---|
| ||
public class GoodComparison { public static void main(String[] args) { String one = new String("one""one"); String two = new String("one""one"); boolean result; if (one != null){ one = one.intern(); } if (two != null){ two = two.intern(); } result = one == two; System.out.println(result); } } |
...
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
References
Wiki Markup |
---|
\[[JLS 05|AA. Java References#JLS 05]\] [Section 3.10.5, String Literals|http://java.sun.com/docs/books/jls/third_edition/html/lexical.html#3.10.5] \[[FindBugs 08|AA. Java References#FindBugs 08]\] ES: Comparison of String objects using == or \!= \[[MITRE 09|AA. Java References#MITRE 09]\] [CWE ID 595|http://cwe.mitre.org/data/definitions/595.html] ""Incorrect Syntactic Object Comparison"", [CWE ID 597|http://cwe.mitre.org/data/definitions/597.html] ""Use of Wrong Operator in String Comparison"" |
...
EXP02-J. Do not ignore values returned by methods 04. Expressions (EXP) EXP04-J. Be wary of invisible implicit casts when using compound assignment operators