Object Equality

🙋 Need help? Ask an expert now!

When we looked at object equality in an earlier section with the equals() method for String, we discovered how it was different in functionality than the default equals method for other objects. Take a look at the two different equality functions below.

package exlcode;

public class ObjectEqualityExample {

  public static void main(String[] args) {
    ObjectEqualityTest objectEqualityTest = new ObjectEqualityTest("Java");
    ObjectEqualityTest objectEqualityTestOne = new ObjectEqualityTest("Java");
    ObjectEqualityTest objectEqualityTestTwo = objectEqualityTestOne;
    // checks to see if the reference for the objects are the same
    boolean exampleVariableOne = objectEqualityTest.equals(objectEqualityTestOne);
    boolean exampleVariableTwo = objectEqualityTestOne.equals(objectEqualityTestTwo);
package exlcode;

public class ObjectEqualityTest {

  private String exampleVariableThree;

  public ObjectEqualityTest(String exampleVaraibleThree) {
    this.exampleVaraibleThree = exampleVaraibleThree;

The default method for objects only checks whether two objects have the same reference. It does not look at the values of the objects inside the reference to see if those are the same. Therefore, it will work exactly the same as the "==" operator. That is why exampleVariableTwo returns "true" as the reference of the two variables is the same. Even though objectEqualityTest and objectEqualityTestOne have the exact same statement with the same parameters, it returns "false" because they are two individual objects.

The way to handle this issue in your own work is to create your own equals() method in your class and override the default one. We will learn how to override methods later in the course.

Edit Me on GitHub!

Application Question

Consider the following code segment:

ExampleClass exampleClassOne = new ExampleClass();
            ExampleClass exampleClassTwo = new ExampleClass();
            ExampleClass exampleClassThree = exampleClassTwo;

After this code is executed, which of the following statements will evaluate to TRUE?

I. exampleClassOne.equals(exampleClassThree)
II. exampleClassOne == exampleClassTwo
III. exampleClassOne == exampleClassThree