Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Differnce between == and equals

 
anil kuchana
Ranch Hand
Posts: 404
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hello every1,
please state the difference between == operator and equals method
 
William Brogden
Author and all-around good cowpoke
Rancher
Posts: 13074
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It is absolutely essential to know this one.
The == operator with reference types (ie Objects) evaluates as true if the references are identical - point to the same thing.
With value types (ie primatives) it evaluates as true if the value is identical.
The purpose of the equals method is to return true if two objects have identical content - however, the equals method in the java.lang.Object class - the default method if a class does not override it - returns true only if both references point to the same thing.
In order to be really useful, classes typically override the equals method to test for equality of content. Look at the source code for the equals method in the java.lang.Long class for instance.
public boolean equals(Object obj) {
if ((obj != null) && (obj instanceof Long)) {
return value == ((Long)obj).longValue();
}
return false;
}
Bill
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic