Open In App

Difference Between Equality of Objects and Equality of References in Java

Improve
Improve
Like Article
Like
Save
Share
Report

Equality of objects means when two separate objects happen to have the same values/state. Whereas equality of references means when two object references point to the same object. The == operator can be used to check if two object references point to the same object. To be able to compare two java objects of the same class the boolean equals(Object obj) method must be overridden and implemented by the class. The implementer decides which values must be equal to consider two objects to be equal.

In Java, when the “==” operator is used to compare 2 objects, it checks to see if the objects refer to the same place in memory. In other words, it checks to see if the 2 object names are basically references to the same memory location.

Java




import java.io.*;
  
String obj1 = new String("xyz");
String obj2 = obj1;
  
// now obj2 and obj1 reference the same place in memory
  
if (obj1 == obj2)
    System.out.println("obj1==obj2 is True");
else
    System.out.println("obj1==obj2 is False");


Output:

obj1==obj2 is True

Note in the code above that obj2 and obj1 both reference the same place in memory because of this line: “String  obj2=obj1;”. And because the “==” compares the memory reference for each object, it will return true.

The equals method is defined in the Object class, from which every class is either a direct or indirect descendant. By default, the equals() method actually behaves the same as the “==” operator – meaning it checks to see if both objects reference the same place in memory. But, the equals method is actually meant to compare the contents of 2 objects and not their location in memory.

The Java String class actually overrides the default equals() implementation in the Object class – and it overrides the method so that it checks only the values of the strings, not their locations in memory. This means that if you call the equals() method to compare 2 String objects, then as long as the actual sequence of characters is equal, both objects are considered equal.

Java




import java.io.*;
  
String obj1 = new String("xyz");
String obj2 = new String("xyz");
  
if (obj1.equals(obj2))
    System.out.println("obj1==obj2 is True");
else
    System.out.println("obj1==obj2 is False");


Output:

obj1==obj2 is True


Last Updated : 17 Jul, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads