Sobes.tech
Junior — Middle

Why is the equals() method used in Java for comparing object contents instead of the == operator?

sobes.tech AI

Answer from AI

In Java, the == operator compares object references, meaning it checks whether two variables point to the same object in memory.

The equals() method is intended for comparing the contents of objects — their logical equivalence.

For example, two strings with the same text can be different objects, so == will return false, but equals() will return true:

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().