How Equals Works in Java

I saw some confusion about this matter on a list this morning, so I thought I’d clarify things here:

The object “Object” which all other Java objects extend has an equals method which allows you to check to see if two objects are equal, which means you call equals on any object you want. Objet’s implementation of equals does the following (from the documentation):

The equals method for class Object implements the most discriminating possible equivalence relation on objects; that is, for any reference values xand y, this method returns true if and only if x and y refer to the same object ( x==y has the value true ).

When you compare two instances using ==, you are actually comparing their memory addresses to see if they are references to the same object. This is usually not very useful in the normal course of programming. Whether an object is equal to another object is pretty context-specific, meaning that it depends on the types of objects that you are comparing. Strings are a pretty straightforward case. If one string equals “abc” and another string equals “def”, then if you check to see if they are equal by calling the equals method, it should return false. But if one string equals “abc” and the other string equals “abc”, you don’t want to compare the memory addresses of the two instances (since they will be different), but rather you want to compare the sequence of characters. Therefore, the String object override’s Objet’s equals method with it own implementation which simply compares the sequence of characters. Here’s some code to illustrate the point:

This is true:

String a = "Christian Cantrell";String b = "Christian Cantrell";if (a.equals(b)) {// This code will be executed.}

But this is false:

if (a == b) {// This will evaluate to false.// Different memory addresses.// Do this only to check to see if two// variables point to the same object instance.}

This is true:

if (a == a) {// True because you are comparing the same instance.}

And finally, this is also true:

b = a;if (a == b) {// True because you are comparing the same instance.}

Many other objects override the equals method so that it makes sense contextually. I’ll post more information tomorrow.