rikky rikky - 4 months ago 13x
Java Question

== returning false even after having same hashcode of two strings what might be the reason?

In the following code s1 and s3 are having same hash code but when compared with == it is returning false, s1 == s2 is returning true with same hash code what might be the reason.

String s1 = "hello";
String s2 = "hello";
String s = "hellohi";
System.out.println(s1.hashCode());//hash code is 99162322
System.out.println(s2.hashCode());//hash code is 99162322 same as s1
System.out.println(s1==s2);//returns true
String s3 = s.substring(0,5);
System.out.println(s3.hashCode());//hash code is 99162322 same as s1
System.out.println(s1==s3);//but returns false why?


There's a rule, equal objects must have equal hashcodes, but objects with equal hashcodes are not necessary equal.

For object variables operator == compares references (memory addresses) of operands.

s3 is substring from s, as String is immutable in Java, substring builds new object, so s1 != s3, because s1 and s3 are different objects and have different memory addresses.

s1 == s2 because literals are interned, and both object variables s1 and s2 reference to the same object hello in the string pool.

hashCode for String is calculated based on the string contents, and as s1, s2 and s3 contains hello, hashcode of these strings are equal for each other.