...
Code Block | ||
---|---|---|
| ||
public class GoodComparison { public static void main(String[] args) { String one = new String("one"); String two = new String("one"); boolean result; if (one == null){ result = two == null; } else{ result = one == two || one.equals(two); } System.out.println(result); } } |
NOte Note that the mentioned operators work when dealing with string literals that have constant values (such as in String one = "one" and String two = "two"
. or when the intern
method has been used on both strings to compare pointer references. (See Compliant Solution 2.)
Compliant Solution
If it is desired to keep only one copy of the string in memory, perform quick repeated comparisons and ensure that string1.equals(string2)
is true
, the following Compliant Solution may be used.
...
Using the equality or relational operators to compare objects can lead to unexpected results.
Rule Guideline | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
EXP01- J | low | probable | medium | P4 | L3 |
...