Comparing StringBuffer content with equals

 1.  System.out.println(sb1 == sb2);  

StringBuffer's equals method returns true only when a StringBuffer object is compared with itself. It returns false when compared with any other StringBuffer, even if the two contain the same characters.

This is because "==" checks the reference equality and since both sb1 and sb2 are different object references, so the output in this case is "false"

Still if you want to check if the content is equal in these two StringBuffer Objects, you can use this:

sb1.toString().equals(sb2.toString())

2. System.out.println(sb1.equals(sb2));

This is giving output as "false" because .equals() method has not been overridden in the StringBuffer Class. So it is using the .equals() method from its parent "Object" class. In the object class .equals() has been written to check the reference equality.

Note that sb3.equals(sb4) will return "true" in case of String. Because .equals() method has been overridden in String class to check and match the content of two different Strings.


The equals method of StringBuffer is not overridden from Object, so it is just reference equality, i.e., the same as using ==. I suspect the reason for this is that StringBuffer is modifiable, and overriding equals is mostly useful for value-like classes that you might want to use as keys (though lists also have an overridden equals and StringBuffer is kind of a list, so this is a bit inconsistent).


You are comparing the references to the StringBuffer objects rather than the actual strings within the StringBuffer.

System.out.println(sb1.toString().equals(sb2.toString())) would return true and I assume this is what you had expected or wanted to achieve.

Tags:

Java