Difference between "== operator" and "equals() method"

== Operator:

The "== operator" is used to compare primitives types and objects. While comparing primitives types like int, float, boolean "==" operator works fine. The "== operator" compare two objects based on memory reference. So "==" operator will return true, only if two references which it is comparing is pointing to the exactly same object otherwise "==" will return false.

equals() Method:

The equals() method has been defined in java.lang.Object class and used for comparing two objects on the basis of their contents. In java, if two objects are equal they should have equal hashcode as well. The equals() method has contract with hashcode() method in java that whenever you override equals() method you should also override the hashcode() method.  Default implementation of equals() method is similar to the == operator which returns true if you are comparing two references of same object.
Diagram: "== operator" and "equals() method"



Let us take an example,

class Demo{
public static void main(String []args){
String s1=new String("Java Programming") ;
String s2=new String("Java Programming");
System.out.println(s1==s2);
System.out.printlnl(s1.equals(s2));
}
}
 Output:
false
true

In above example, we have created two objects, object s1 with contents "Java Programming" and object s2 with contents "Java Programming".

Diagram: Memory representation of object s1 and s2

As we are saying == operator is meant for reference comparison, if both the references are pointing towards the same object then only == operator will return true.

But in above example, object s1 and object s2 are pointing to different objects i.e. reference wise and address wise objects s1 and s2 are not equal, So s1==s2 returns false.

Even though object s1 and s2 are pointing to different objects but their contents are same. So s1.equals(s2) returns true.

Comments

Post a Comment

Popular posts from this blog

Java 5: Varargs

Method Overloading Vs Method Overriding