permaculture playing cards
The moose likes Beginning Java and the fly likes Comparison Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Comparison "equals" and "=="" Watch "Comparison "equals" and "=="" New topic

Comparison "equals" and "=="

Thomas Markl
Ranch Hand

Joined: Mar 08, 2001
Posts: 192
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
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

Joined: Dec 07, 2002
Posts: 2
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

Joined: Jul 22, 2000
Posts: 9059
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.

"Yesterday is history, tomorrow is a mystery, and today is a gift; that's why they call it the present." Eleanor Roosevelt
karl koch
Ranch Hand

Joined: May 25, 2001
Posts: 388
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.

Mark Mokris
Ranch Hand

Joined: May 08, 2002
Posts: 61
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

Joined: Dec 04, 2002
Posts: 133
Yes. And you also need to override hashCode.

I agree. Here's the link:
subject: Comparison "equals" and "=="
It's not a secret anymore!