Object o1 = new Object();
Object o2 = new Object();
//o1=o2;
System.out.println(o1.equals(o2));
It returns false
. It can return true
, if the comment is removed.
Why isn't the same thing applicable to the String
class?
String s1=new String();
String s2=new String();
System.out.println(s1.equals(s2));
It returns true
. Why? (because String
uses interns or something else involved?)
Best Answer
Because equals() for String compares the content, not the object itself.
(Link to the source of String.equals())
Versus the equals for Object:
(Link to the source of Object.equals())
Also, don't forget the contract of the
equals()
function:Also recommended reading: