Given this:
String s1= new String("abc");
String s2= new String("abc");
String s3 ="abc";
System.out.println(s1==s3);
System.out.println(s1==s2);
System.out.println(s1.equals(s2));
System.out.println(s1.equals(s3));
System.out.println(s1.hashCode());
System.out.println(s2.hashCode());
System.out.println(s3.hashCode());
Output is:
false
false
true
true
96354
96354
96354
Here == is giving false for each object but the hashcode for each String object is same. Why is it so?
==does compare real equality of objects (I mean – both references point to the same object), not their content, whereas.equalcompares content (at least for String).aandbare pointing to different objects.Notice also that if objects are equal then their hashchodes must be the same, but if hashcodes are the same, it doesn’t mean that objects are equal.