Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Added 2 CSs

...

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 1

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

Code Block
bgColor#ccccff
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 || two.equals(one);
    }
    else{
    	result = one == two || one.equals(two));
    }
   System.out.println("Equal"result); //printed
  }
}

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 2

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

Code Block
bgColor#ccccff

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

Risk Assessment

Using the equality or realtional relational operators to compare objects may lead to unexpected results.

...