Junior — Middle
Explain the difference between using the equals method and the == operator for object comparison in Java.
sobes.tech AI
Answer from AI
In Java, the == operator compares references to objects, meaning it checks whether two variables point to the same object in memory. If the references match, == returns true; otherwise, it returns false.
The equals() method is intended for logical comparison of object contents. By default (in the Object class), it behaves like ==, but many classes (such as String, Integer, and user-defined classes) override this method to compare the actual data inside objects.
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
Therefore, to compare the contents of objects, always use equals(), and use == to check for reference identity.