Junior — Middle
How to distinguish between object comparison using the equals method and using the == operator in Java?
sobes.tech AI
Answer from AI
In Java, the == operator and the equals() method serve different purposes when comparing objects:
-
==compares references to objects, i.e., checks whether two variables point to the same object in memory. -
equals()compares the content of objects according to the logic defined in the overridden method.
Example:
String a = new String("test");
String b = new String("test");
System.out.println(a == b); // false, different objects
System.out.println(a.equals(b)); // true, same content
If a class does not override equals(), its default implementation from Object behaves like ==.
Therefore, for comparing values of objects (e.g., strings, collections), equals() should always be used, while == checks object identity.