What is the logic behind == returning false when two reference variables are referring to same Object having same hash code values?

public class One {  
    public static void main(String[] args) {        
        One o = new One();
        One o1 = o; 
        System.out.println(o.toString());                                       
        System.out.println(o1.toString());                                      
        System.out.println(o.hashCode());                                       
        System.out.println(o1.hashCode());                                      
        
        // Why does it print false ?
        System.out.println(o.toString()==o1.toString());    // false                    
        System.out.println(o.hashCode()==o1.hashCode());    // true                 
        System.out.println(o.equals(o1));                   // true
                            
        System.out.println(o.toString().hashCode()==o.toString().hashCode());   // true 
    }
}
2

There are 2 best solutions below

3
On

The line with

System.out.println(o.toString()==o1.toString());    // false  

has a toString(). Each toString() creates a new String Object, which are different Objects that have their own memory locations. So the == actually checks the memory addresses between those new String Objects.

Always compare strings with String#equals, not with ==.

0
On

== sign checks the memory addresses of objects being compared. In your case, toString() method creates two different String objects stored in two different places. That's why you get false when you try to compare them.
On the other hand, equals() checks the equality of contents of the objects. For your own data types, you should override this method to use it.
hashCode is some sort of a unique identification number for the contents of the objects. That is to say, objects that are equal to each other must return the same hashCode.