Hi When I use the following code,
String s="cow";
String c="cow";
String s1=new String("cow");
String s2=new String("cow");
System.out.println(s1==s2);//false
System.out.println(s==s1);//false
System.out.println(s==c);//true
System.out.println(s.hashCode());//1000911
System.out.println(s1.hashCode());//1000911
System.out.println(s2.hashCode());//1000911
System.out.println(c.hashCode());//1000911
As per my understanding, if we use ==, the control will check for references but not for objects. But why is that in the above example, s1==s2 is false, eventhough they have the same hashCode? Strings are immutable and when a new string is initialised, the control checks for the existing strings in the string pool and if it matches the existing one with the new one, then the control will assign the new variable to the existing string object. So I should get true when I use s1==s2 since their hashcodes are equal. But I am getting false.
Any explanation on this issue why we are getting false will be appreciated.
Regards,
Kiran.