Wednesday, April 21, 2010

== operator vs equals() method


First of all we have to understand about == operator.
The figure shows that there is two object of Student class.
class Student{
int id;


}









There is two reference variable s1 and s2 referring to the same object of memory address 1001, i.e. the value of reference variable s1 and s2 1001. While, s3 is referring to different object with memory address 1010.
If we compare s1==s2 it will return true because both are referring to the same object.

However, the object on memory address 1010 having the same id (id=1) as referred by s1 even s1==s3 or s2==s3 will return false because they posses different memory addresses i.e. they are referring to two different objects.
It means, == operator compare between the value of reference variable rather than the content of the object.
Now, come to the equals(). This method is defined within Object (the super cosmic) class. In Object class the equals() method is defined in such way that it works just same as == operator. It means, equals() method provided by Object class also compares the value of reference variable instead of content of objects.
But it provides us the facility that we can override the equals() method and compare two objects on the basis of our requirement, i.e. to compare two object on the basis of its content, we can override equals().
e.g. in above Student class we can override equals() like
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Student other = (Student) obj;
if (this.id != other.id) {
return false;
}
return true;
}
and now if we compare between s1, s2 and s3, if id of object is same then equals() method will return true but s1==s3 or s2==s3 will return false.

2 comments:

  1. nice article. this was classic question few years back but now days interviewer are mostly asking writing code fore equals and hashcode method in java. I have shared some tips on writing equals method in java with example you may find useful.

    ReplyDelete
  2. I have read your blog its very attractive and impressive. I like it your blog.

    Java Training in Chennai Java Training in Chennai | Core Java Training in Chennai | Java Training Institutes

    Online Java Training Java Online Training | Java J2EE Online Training | JavaEE Training Institute in Chennai

    ReplyDelete