In Java, the equals()
method is used to compare the equality of two objects based on their content, while the ==
operator is used to compare the references of two objects to see if they point to the same memory location. The main differences are:
equals()
method can be overridden by a class to define its own equality criteria, whereas the ==
operator cannot be overridden.equals()
method compares the values of objects, whereas the ==
operator compares the memory addresses.equals()
method compares the memory addresses similar to the ==
operator unless it is overridden.public class Main {
public static void main(String[] args) {
String str1 = "Hello";
String str2 = new String("Hello");
String str3 = str1;
System.out.println(str1.equals(str2)); // Output: true
System.out.println(str1 == str2); // Output: false
System.out.println(str1.equals(str3)); // Output: true
System.out.println(str1 == str3); // Output: true
Integer num1 = 5;
Integer num2 = 5;
System.out.println(num1.equals(num2)); // Output: true
System.out.println(num1 == num2); // Output: true
Integer num3 = 200;
Integer num4 = 200;
System.out.println(num3.equals(num4)); // Output: true
System.out.println(num3 == num4); // Output: false
}
}
true
false
true
true
true
true
true
false
In this example, we have variables str1
, str2
, and str3
representing strings, and variables num1
, num2
, num3
, and num4
representing integers.
When comparing strings using the equals()
method, it compares the content of the strings. In the example, str1.equals(str2)
returns true
because the content of both strings is “Hello”. However, when using the ==
operator to compare the string objects themselves, str1 == str2
returns false
because they refer to different memory locations.
When comparing references using the ==
operator, it checks whether the variables refer to the same object in memory. In the example, str1 == str3
returns true
because both variables reference the same “Hello” string object in memory.
Similarly, when comparing Integer
objects using the equals()
method, it compares the values of the integers. In the example, num1.equals(num2)
returns true
because both variables have the value 5. However, when using the ==
operator to compare the Integer
objects, num1 == num2
returns true
because the values fall within the range of cached Integer
objects.
For larger integer values, as seen in num3
and num4
, the ==
operator returns false
because the values are outside the range of cached Integer
objects, even though num3.equals(num4)
returns true
because the values are equal.
This example highlights that the equals()
method compares the content or values of objects, while the ==
operator compares the references or memory addresses of objects.