Search code examples
javageneric-collections

Java confused about == in the overridden equals method


This is the piece of code I used from the SCJP book. I understand that == compares the memory location of the objects to find the equality and .equals compares the hashcode to determine the equality.

My question is in the below snippet, in the overrided equals method we compare :

(((Moof)o).getMoofValue()) == this.getMoofValue()

in the above code, does the == compare the memory location of the string value? If it does then it should be false. But it returns true. How does the == work here?

public class EqualsTest {

    public static void main(String args[]){
        Moof one = new Moof("a");
        Moof two = new Moof("a");
        if(one.equals(two)){
            System.out.println("Equal");
        }
        else{
            System.out.println("Not Equal");
        }
    }
}



    public class Moof {
        private String moofValue;
        public Moof(String i){
            this.moofValue = i;
        }
        public String getMoofValue(){
            return this.moofValue;
        }
        public boolean equals(Object o){
            if((o instanceof Moof) && (((Moof)o).getMoofValue()) == this.getMoofValue()){
                return true;
            }
            return false;
        }
    }

Solution

  • (Moof)o).getMoofValue()) == this.getMoofValue()) 
    

    here..You are still comparing references to the same String object in the String pool. Because String literals are interned automatically.

    Edit :

    public class TestClass {
    
        String s;
    
        TestClass(String s) {
            this.s = s;
        }
    
        public static void main(String[] args) {
    
            String s1 = new String("a");
            String s2 = new String("a");
            System.out.println(s1 == s2);
    
            TestClass t1 = new TestClass("a");
            TestClass t2 = new TestClass("a"); 
            System.out.println(t1 == t2);      // here you are comparing t1 with t2, not t1.s with t2.s so you get false... 
            System.out.println(t1.s == t2.s); // t1.s and t2.s refer to the same "a", so you get true.
    
         TestClass t3 = new TestClass(s1);
         TestClass t4 = new TestClass(s2);
         System.out.println(t3.s == t4.s);      // false because s1 and s2 are 2 different references. 
        }
    
    }
    O/P : 
    false
    false
    true
    false