...
For ==
to return true
for two String
references, they must point to the same underlying object. This noncompliant example declares two different String
objects with the same values, however, they compare unequal since because they constitute different object references.
...
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); } } |
The NOte that the mentioned operators now seemingly work while 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)
...
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){ one = one.intern(); } if (two != null){ two = two.intern(); } result = one == two; System.out.println(result); } } |
Note howeverHowever, note that the performance gains achieved by doing so may be meeker than the benefits of having more robust code that also takes non-constant and non-interned values. Moreover, such behavior the use of constant and interned values encourages ambiguity that hinders selection of proper methods for comparing String
objects.
...
Wiki Markup |
---|
*EXP03:* In general, for any two objects, it is permissible to compare their elements provided that the class is a singleton. The use of static factory methods over constructors facilitates instance control which in turn limits the effective number of instances of an immutable class to one. As a result, for two objects {{a}} and {{b}}, {{a.equals(b)}} is {{true}} when {{a == b}} \[[Bloch 08|AA. Java References#Bloch 08]\]. The {{String}} class does not meet these requirements and consequently, does not possess these characteristics. |
...
Using the equality or relational operators to compare objects may can lead to unexpected results.
...