Compare two StringBuilder objects (or StringBuffer) – equals

This example shows how to compare two StringBuilder objects in Java. Since the StringBuilder is a drop-in replacement for StringBuffer, this applies to compare two StringBuffer objects as well.

How to compare two StringBuilder objects in Java?

The StringBuilder (or StringBuffer) class has not implemented the equals method, it inherits the version defined in the Object class. The equals method of the Object class compares the object references, not the content.

So if you want to compare two StringBuilder object contents, comparing them using the equals method does not work.

Output

As you can see in the above example, even though the contents of both of the StringBuilder objects are the same, the equals method returned false. The reason is, they both refer to different objects.

How to compare StringBuilder objects using the content?

We can convert the StringBuilder object to String and then use the equals method of the String class to compare the content as given below.

Output

This approach needs an additional step of converting StringBuilder to String which may not be efficient in terms of performance in some cases. Here is the source code of the toString method of the StringBuilder class.

As you can see, it creates a new String object using the internal character buffer array and returns it.

What is the preferred way to compare?

I would first check if both StringBuilder object has the same length i.e. the same number of characters. It will be a quick operation and will save us from comparing the objects if the length is not the same.

If they do have the same number of characters, I would compare each character of one StringBuilder object to another StringBuilder object as given below.

Output

I did not perform any benchmarking but I think this method should perform better than using the toString method to compare the StringBuilder or StringBuffer objects, especially in the cases where you want to compare lots of StringBuilder objects having content of different lengths.

This example is a part of the Java StringBuffer tutorial and Java StringBuilder tutorial.

Please let me know your views in the comments section below.

About the author

RahimV

RahimV

My name is RahimV and I have over 16 years of experience in designing and developing Java applications. Over the years I have worked with many fortune 500 companies as an eCommerce Architect. My goal is to provide high quality but simple to understand Java tutorials and examples for free. If you like my website, follow me on Facebook and Twitter.

Add Comment

Your email address will not be published. Required fields are marked *