Why does "==" sometimes work with String.trim?

Viewed 244

I have the following code

public static void main(String... args) {

    String s = "abc";
    System.out.println(s.hashCode());
    String s1 = " abc ";
    System.out.println(s1.hashCode());
    String s2 = s.trim();
    System.out.println(s2.hashCode());
    String s3 = s1.trim();
    System.out.println(s3.hashCode());
    System.out.println();
    System.out.println(s == s1);
    System.out.println(s == s2);
    System.out.println(s == s3);
}

OP:

96354
32539678
96354
96354

false   -- Correct
true    -- This means s and s2 are references to the same String object "abc" .
false   -- s3=s1.trim()... which means s3="abc" yet s==s3 fails.. If the above conditon were to be considered (s==s2 is true..) , this should also be true.. 

Why am i getting "false" when i check s==s3 ?..

5 Answers
Related