Difference between equals method and equality operator in java

Ans) == operator is binary operator used to compare the primitives and objects in java. Primitives such as int, float, boolean can use == to compare the values of primitive variables. But if == is used for comparing objects, then it compares the references of the object, == will return only true when two objects point to same memory location in JVM.

public boolean equals (Object o) is the method provided by the Object class. By default, the equals() method actually behaves the same as the "=="" operator, meaning it checks to see if both objects reference the same place in memory. But since the method can be overriden like for String class. equals() method can be used to compare the actual values of two objects. For e.g. String class overrides equals method to compare the actual values. Default implementation of equals method in String class.
//implementation of String.class equals() method
public boolean equals(Object anObject) {
    if (this == anObject) {
        return true;
    }
    if (anObject instanceof String) {
        String anotherString = (String) anObject;
        int n = value.length;
        if (n == anotherString.value.length) {
            char v1[] = value;
            char v2[] = anotherString.value;
            int i = 0;
            while (n-- != 0) {
                if (v1[i] != v2[i])
                        return false;
                i++;
            }
            return true;
        }
    }
    return false;
}

It is advisable, to override the equals method( Why to override) in most of the user defined java objects.
String str1 = "MyName"; 
String str2 = "MyName";
String str3 = str2;
String str4 = new String("MyName");

str1 == str2 // true
str1 == str3 //true
str1 == str4 //false
str1.equals(str2) //true
str1.equals(str3) //true
str1.equals(str4) //true
The third case returns false , since new String("MyName") , create a new variable at different memory location.

Subscribe to get latest updates.

© 2015 Java Questions | Sitemap