You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 2 Next »

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

Non-Compliant Code Example

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

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.

public class GoodComparison {
  public static void main(String[] args) {
    String one = new String("one");
    String two = new String("one");
    if(one.equals(two))
      System.out.println("Equal"); //printed
  }
}

The mentioned operators 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. 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.

References

Findbugs, ES: Comparison of String objects using == or !=
JLS 3.10.5 String Literals

  • No labels