Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Java defines equality operators == and != and relational operators such as <=,>=,>,<. When it comes to string String object reference comparisons, these manifest as traps that an amateur programmer may unintentionally fall victim to.

...

For == to return true for two string String references, they must point to the same underlying object. This noncompliant example declares two different string String objects with the same values, however, they compare unequal since they constitute different object references.

Code Block
bgColor#FFcccc
public class BadComparison {
  public static void main(String[] args) {
    String one = new String("one");
    String two = new String("one");
    if(one == two)
      System.out.println("Equal"); //not printed
  }
}

Compliant Solution

...

To be compliant, use the object1.equals(object2) method when comparing string values.

...

The mentioned operators now seemingly work while 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.

...

Note however, 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 encourages ambiguity that hinders selection of proper methods for comparing String objects.

Exceptions

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 only 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.

...