Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Comparison "equals" and "=="

 
Thomas Markl
Ranch Hand
Posts: 192
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why is it possible to compare to objects with
equals and it compiles and when I compare them with "==" there is a compiler error "incompatible
types".
Why does "==" perform a types check and equals doesn't?
class Employee {}
class ObjectTest1c {
public static void main ( String args [ ] ) {
Integer ar1 = new Integer(1);
Employee emp = new Employee();

//System.out.println(ar1 == emp) ; //compiler error
System.out.println(ar1.equals(emp)) ;
}
}
 
narasimharao vutukuru
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
compiler tries to convert operand type before comparison when u use == operator.equals() also do the conversion.but here this converts to Object type.since Object is super class all the objects can convert to Object type.
 
Marilyn de Queiroz
Sheriff
Posts: 9065
12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A compile-time error occurs if it is impossible to convert the type of either operand to the type of the other by a casting conversion Java Language Specification

The method equals defines a notion of object equality, which is based on value, not reference, comparison. Java Language Specification
myClassObject.equals( yourClassObject ) does not depend on whether myClassObject and yourClassObject are objects of the same class. But they must both be Objects (not primitives).

For example, a date object of the java.sql.Date may be equal to a date object of the java.util.Date class if they are both the same date even though the dates were instantiated from different classes.
 
karl koch
Ranch Hand
Posts: 388
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi
the == is used to compare two references, that is if two references point to the sae object.
the equals() method (inherited from java.lang.Object) checks if two objects have the same content.



k
 
Mark Mokris
Ranch Hand
Posts: 61
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A related question...
Don't you have to override the equals() method in any classes that you the programmer create in order to "define" your own notion of equality? The default behavior of equals( ), inherited from Object, still just compares object references, doesn't it?
 
Jon Strayer
Ranch Hand
Posts: 133
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes. And you also need to override hashCode.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic