With object references x==y will only be true if x and y are referencing the same object. The values for x.equals(y) and y.equals(x) depends on your implementation of the equals() method in the specific x or y class.
Suppose you have a dog. Attached to the dog is a collar and two leads. If you hold one lead and I hold the other lead, then we can ask the question "are we holding onto the same dog". That's what "==" does. We follow the leads we are holding and we meet together at the same dog: Fido.
On the other, hand, we can each be holding a lead attached to a dog. We compare our dogs: same name? same breed? same age? same colour? We could come to the conclusion we have identical kinds of dog, that my dog ".equals" your dog. But following the dogs' leads does not mean we find the same dog at their ends. If we do find the same dog, we must agree that our ".equals" criteria also holds, that we call that dog Fido, that it is a german shepard, it is 2 years old, it is light brown.
So "==" implies ".equals", but ".equals" does not necessarily imply "==".
Barry, Thanks for the ans. So basically, If the == test passes then the .equals() test will also necessarily pass. but if the .equals() test passes, it not necessary that the == will pass. Is this correct?
Joined: Aug 03, 2002
Originally posted by Amitabha Batranab: Barry, Thanks for the ans. So basically, If the == test passes then the .equals() test will also necessarily pass. but if the .equals() test passes, it not necessary that the == will pass. Is this correct?
Theoretically, you can create a class which overrides the equals method in a way the violates the "Java contract" of equals. You can, for example, create an equals method that always returns false. This is stupid, but it will compile and run.
In this case, the == method could be true for two references that point to the same object, but the equals method would return (obviously) false.
The equals method behaves, if it is overridden by YOU, however you want it to behave. You can naturally make some stupid decisions and get situations where an object is not equal to itself.
You should, in practice, never do this, but it is POSSIBLE.