Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: changed "children"->"subclasses" and other minor edits

Java defines the equality operators == and != for testing reference equality, but uses the Object.equals() method and its children subclasses for testing abstract object equality. Naive programmers often confuse the intent of the == operation with that of the Object.equals() method. This confusion is frequently seen in the context of String processing.

As a general rule, use the Object.equals() method to check whether two objects are abstractly equal to each other. Reserve use of the equality operators == and != for testing whether two references specifically refer to the same object (this is reference equality). See also guideline MET13-J. Classes that define an equals() method must also define a hashCode() method.

This use of the equality operators also applies to numeric boxed types (for example,Byte, Character, Short, Integer, Long, Float, and Double), although the numeric relational operators (such as <, <=, >, and >=) produce results that match those provided for arguments of the equivalent primitive numeric types. See guideline EXP03-J. Avoid the equality operators when comparing values of boxed primitives for more information.

...

Code Block
bgColor#FFcccc
public class ExampleComparison {
  public static void main(String[] args) {
    String str1 = new String("one");
    String str2 = new String("one");
    boolean result;
    // test below is redundant in this case, but required for full generality
    if (str1 == null) { 
      result = str2 == null;
    }
    else {
      result = str1 == str2;
    }
    System.out.println(result); // prints false
  }
}

Compliant Solution (Object.equals())

This compliant solution uses the Object.equals() method when comparing string values.

Code Block
bgColor#ccccff
public class GoodComparison {
  public static void main(String[] args) {
    String str1 = new String("one");
    String str2 = new String("one");
    boolean result;
    if (str1 == null) {
      result = (str2 == null);
    } else {
      result = str1.equals(str2);
    }
    System.out.println(result);
  }
}

Compliant Solution (String.intern())

Reference equality behaves like abstract object equality when comparing two strings that are each the result of the String.intern() method. When a task requires keeping only one copy of each string in memory, as well as performing quick repeated string comparisons, this compliant solution may be used.

...