Why can't objects in Java be compared using the '==' operator?
sobes.tech AI
Answer from AI
The == operator for object comparison in Java by default compares references, not their content. It checks whether two variables point to the same object instance in memory.
To compare the content of objects, the equals() method should be used. The equals() method is defined in the Object class and can be overridden in your classes to implement specific content comparison logic.
Example of using == and equals():
String s1 = new String("hello");
String s2 = new String("hello");
String s3 = s1;
// Reference comparison - false, as these are different objects
System.out.println(s1 == s2);
// Reference comparison - true, as s1 and s3 point to the same object
System.out.println(s1 == s3);
// Content comparison - true, as the strings are equal
System.out.println(s1.equals(s2));
Primitive data types (int, boolean, char, etc.) are an exception, for which the == operator compares their actual values directly. For wrapper objects of primitive types (Integer, Boolean, Character, etc.), the == operator also compares references, not values, unless auto-boxing/unboxing is used for small, cached values (e.g., Integer from -128 to 127).