Since Java doesn’t support operator overloading, ==
behaves identical
for every object but equals()
is method, which can be overridden in
Java and logic to compare objects can be changed based upon business
rules.
Main difference between ==
and equals in Java is that "=="
is used to
compare primitives while equals()
method is recommended to check
equality of objects.
String comparison is a common scenario of using both ==
and equals()
method. Since java.lang.String class override equals method, It
return true if two String object contains same content but ==
will
only return true if two references are pointing to same object.
Here is an example of comparing two Strings in Java for equality using ==
and equals()
method which will clear some doubts:
public class TEstT{
public static void main(String[] args) {
String text1 = new String("apple");
String text2 = new String("apple");
//since two strings are different object result should be false
boolean result = text1 == text2;
System.out.println("Comparing two strings with == operator: " + result);
//since strings contains same content , equals() should return true
result = text1.equals(text2);
System.out.println("Comparing two Strings with same content using equals method: " + result);
text2 = text1;
//since both text2 and text1d reference variable are pointing to same object
//"==" should return true
result = (text1 == text2);
System.out.println("Comparing two reference pointing to same String with == operator: " + result);
}
}