Whenever I use equals() method with two different StringBuffer objects, I get the result as false, but when I use equals() method with two different String objects, I get the result as true. Why?
String s=new String("434");
String s1=new String("434");
System.out.println(s.equals(s1));//true
StringBuffer s=new StringBuffer("434");
StringBuffer s1=new StringBuffer("434");
System.out.println(s.equals(s1));//false
StringBuffer does not override equals(). As such, Object.equals() is called, which compare the object identity (the memory address). String does override equals and compare the content.
StringBuffer does not override Object#equals(), so you're experiencing reference identity-based checks rather than value-based checks. As these StringBuilder instances are distinct, each with different memory locations, the base Object#equals() implementation will always return false.
Here's the definition as of Java 6:
public boolean equals(Object obj) {
return (this == obj);
}
See the problem?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With