I noticed that when equals() is used to compare between two String objects it works fine. But when I compare two StringBuffer objects or two StringBuilder objects or mix of String and Builder and Buffer, equals() doesn't work even though I give same string value to the two objects being compared.

However when I say it doesn't work, I mean it compiles fine, but it just says unequal according to if loop.
Then I checked Java docs online under Buffer and Builder API and equals() is not listed under methods summary for them but it is listed for String.
So my understanding is that equals doesn't work at all for Buffer and Builder but only for String? Correct me if I'm wrong please.

And second, if equals is not available for Buffer and Builder, then what is the alternate to compare the different object's contents for them?

P.S. I have typed Buffer and Builder for StringBuffer and StringBuilder as a typing convenience. Please don't confuse otherwise. Thanks.

Recommended Answers

All 5 Replies

every type of Object (so, every class in Java) has an equals method.

Well then when I compiled this code:
StringBuffer sb1 = new StringBuffer("Hello");
StringBuffer sb2 = new StringBuffer("Hello");
System.out.println(sb1.equals(sb2));

the output is false!
Why is that?

The equals method is defined in the Object class, so in the API docs you will find it listed in the "inherited methods" section. That version of equals tests for the the objects being exactly the same object (at the same memory address), so that's what you get if a class does not override it like String does.
In your test code you create two StringBuffers. They have similar data but they are two distinct different objects. StringBuffer does not override equals, so it's inherited from Object, and returns false in this case.

that's where inheritance kicks in.
String, just as tons of other classes, overrides the equals method of the Object class, and thus implement it's own logic, while the StringBuffer class doesn't.
the String equals will check whether or not the value of the Object is the same, but the equals of the Object class, will check whether or not the two Objects are identical Objects, not just Objects with an identical value.

since StringBuffer doesn't override the equals method, since it inherits and thus uses the equals method from the Object class, it will check whether or not the two objects are the very same object, which they are not, hence, the result is false.

Thanks guys!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.