The == operator compares
values. Applied to primitives like int or boolean, this is straight forward. But applied to object variables, this operator simply compares
references (i.e., memory addresses). Therefore, under the == operator, two object variables are "equal" only if they reference the same instance.
In contrast, the equals
method is intended for a deeper comparison of instances. In the base class of Object, equals is implemented in the same manner as the == operator. However, in any other class, the equals method should be overridden to provide a meaningful result. What exactly it means for two different instances to be "equal" depends on the class.
For example, suppose you have a class called MacComputer. Two
different instances of MacComputer might be considered "equal" if they are both 12" PowerBooks with a 1.5 GHz G4 processor and 512 MB of RAM. In this example, the equals method in the class MacComputer would be overridden to compare 3 fields: model (PowerBook12), processor (G4_1.5), and ram (512). It's up to the programmer to decide what exactly "equals" means for any particular class.
Many (not all) classes in the
Java API have an overridden equals method. For classes that do
not override equals (or are not derived from any superclass that overrides equals), the default implementation of Object is invoked -- a simple comparision of references. To see how equals is implemented in a particular class of the API, check the
documentation.
[ November 12, 2005: Message edited by: marc weber ]