Wednesday 1 May 2013

Difference between ==, equals and hashcode in java


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


==  Compares real equality of Objects (i.e) both references should point to the same object, not their content. 
.equal Compares content of a object.            String a = new String("aa");
    String b = new String("aa");
 
           a and b are pointing to different objects.
Hashcode  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.


No comments:

Post a Comment