Sobes.tech
Junior

Why can't objects in Java be compared using the '==' operator?

sobes.tech AI

Answer from AI

The == operator compares object references in memory, not their contents. To compare the contents of objects, you should use the equals() method.

For example:

// Comparing objects using == and equals()
String s1 = new String("hello");
String s2 = new String("hello");

System.out.println(s1 == s2);       // false (different references)
System.out.println(s1.equals(s2));  // true (same content)

Primitive data types (byte, short, int, long, float, double, boolean, char) are exceptions, for which the == operator compares their values.