Let's understand the == operator and equals method first
== operator
In Java, when the == operator is used, it checks to see if the two objects are basically references to the same memory location or not.
equals() method
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 references the same place in memory but, the equals() method is actually meant to compare the content of two objects, and not their location in memory.
Let's check examples for both cases:
== operator
String obj1 = new String("xyz"); String obj2 = new String("xyz"); if ( obj1 == obj2 ) System.out.println("obj1 == obj2 is TRUE"); else System.out.println("obj1 == obj2 is FALSE");
Output:
obj1 == ob2 is FALSE
Explanation:
Even though the strings have the same exact characters ("xyz"), they have different locations in memory.
The Java String class actually overrides the default equals() method implementation in the Object class - where it checks only the values of the strings and not their locations in memory. This means that if you call the equals() method to compare two String objects, then as long as the actual sequence of characters is equal, both objects are considered equal.
equals() method
String obj1 = new String("xyz"); String obj2 = new String("xyz"); if ( obj1.equals(obj2) ) System.out.println("obj1.equals(obj2) is TRUE"); else System.out.println("obj1.equals(obj2) is FALSE");
Output:
obj1.equals(obj2) is TRUE
So, how is the equals() method behaviour different?
Simple - the equals() method is overridden to get the desired functionality whereby the object contents are compared instead of the object locations.The Java String class actually overrides the default equals() method implementation in the Object class - where it checks only the values of the strings and not their locations in memory. This means that if you call the equals() method to compare two String objects, then as long as the actual sequence of characters is equal, both objects are considered equal.