Rahul Shivsharan Rahul Shivsharan - 5 months ago 10
Java Question

If two objects are having same hashCode and qualify equality by equals, than why they fail for ==

Please follow the below code,

String s1 = "ABC";
String s2 = new String("ABC");
String s3 = "ABC";

System.out.println(s1.hashCode()); // 64578
System.out.println(s2.hashCode()); // 64578

System.out.println(" s1 == s2 "+(s1 == s2)); // s1 == s2 false
System.out.println(" s1 == s3 "+(s1 == s3)); // s1 == s3 true

Here, both String s1 and s2 have same hashcode and qualify by equals, but fail equality by ==, why ?

Is it because s1 and s2 are different objects though both having the same hashcode and qalify by eqauls, if yes how come, please explain me ?

Also, please look at the below example,

class Employee{
private Integer employeeCode;

Employee(Integer empCode){
this.employeeCode = empCode;

public int hashCode(){
return this.employeeCode * 21;

public boolean equals(Object o){
Employee emp = (Employee) o;

return this.employeeCode.equals(emp.employeeCode);

public class HashCodePractise01{

public static void main(String [] args){
Employee e1 = new Employee(1);
Employee e2 = new Employee(1);

System.out.println(e1.hashCode()); // 21
System.out.println(e2.hashCode()); // 21
System.out.println("e1.equals(e2) "+(e1.equals(e2))); // e1.equals(e2) true
System.out.println("e1 == e2 "+(e1 == e2)); // e1 == e2 false

In the above example also, both employee objects have same hashcode and qualify equality by .equals method but still they fail equality in ==.

In both the above cases, why are they two different objects ? please explain


Two Objects in Java will only ever evaluate to == if they share the same memory location (i.e. if they are literally the SAME object).

In your first example, S1 and S3 are equal because string are immutable, and, so, those literals can be smartly converted to a single cached string by java at compile-time (I think this happens at compile-time, could be runtime. I'm a bit fuzzy on java specifics, feel free to provide an edit if anyone knows for certain).