The == with Strings Trap : Comparison Operators « Operators « SCJP






The compiler optimizes storage of String literals by reusing them. 

public class MainClass {
  public static void main(String[] argv) {
    String s1 = "YES";
    String s2 = "YES";
    // The String literal "YES" appears in both lines 1 and 2,
    // but the compiler creates only one String object, referred to by both s1
    // and s2.

    if (s1 == s2){
      System.out.println("equal");

    }
    String s3 = new String("YES");
    String s4 = new String("YES");

    if (s3 == s4){
      System.out.println("s3 eq s4");

    }

  }
}








2.6.Comparison Operators
2.6.1.Comparison Operator Summary
2.6.2.Comparison operators <, <=, >, >=, = =, and != return a boolean result.
2.6.3.Comparison operators are commonly used to form conditions
2.6.4.The Ordinal Comparisons Operators: <, <=, >, and >=
2.6.5.It is acceptable to compare the float value to the char variable c.
2.6.6.Ordinal comparisons are not applicable to any non-numeric types.
2.6.7.The Equality Comparison Operators: == and != for primitive types
2.6.8.The Equality Comparison Operators: == and != for variables of object type
2.6.9.You should not use these operators to compare the contents of objects.
2.6.10.To do a content comparison, use equals() method rather than the == or != operator.
2.6.11.For object references, the == operator returns true only if both references are to the same object.
2.6.12.Define your own equals Method
2.6.13.The == with Strings Trap
2.6.14."Equality" Operators
2.6.15.Equality for Reference Variables
2.6.16.Equality for Enums