Junior — Middle
What is the difference between the `==` operator and the `equals()` method when comparing objects 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. The equals() method is intended for comparing the contents of objects, i.e., logical equality.
For 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 the equals() method, it behaves by default like == (comparing references). Therefore, to correctly compare objects by content, it is important to override equals().