Java String Handling

Java StringBuilder clear example, how to empty StringBuilder (StringBuffer)

Java StringBuilder clear example shows how to clear contents of StringBuilder or StringBuffer object. Example also shows how to empty StringBuilder/StringBuffer object in Java.

How to clear StringBuilder or StringBuffer in Java?

Suppose you have a StringBuilder object being used inside a loop and you want to empty its contents for each iteration of the loop. In such cases, you can clear the contents of the StringBuilder using below given ways.

1) Clear StringBuilder by assigning a new object

This method assigns a new StringBuilder object having no content to the existing reference. This is not exactly clearing the same object, but to assign a new empty object to the same reference.



2) Clear StringBuilder using delete method

You can use delete method of StringBuilder class to selectively delete certain characters from it or you can use it to empty the contents.

The delete method accepts two parameters, start index and end index. To clear the contents, we are going to provide 0 as start index and length of the StringBuilder object as end index to clear everything it has.



As you can see from the output, contents of the StringBuilder is cleared at the start of the loop.

3) Clear StringBuilder using setLength method

You can use setLength method to clear the contents of the StringBuilder object.

For clearing the contents of the StringBuilder, we are going to pass 0 as new length as shown in below example.



What is the best way to clear the StringBuilder?

Now that we have seen three different methods to clear the StringBuilder, you may have this question. Well, the best way to clear the StringBuilder is to use setLength method (3rd option).

Why? Because the first option creates a new StringBuilder object for each iteration of the loop. Object creation is a costly operation because it involves allocating new memory for the new object. Plus, garbage collection has to collect the old unused object. You should avoid this option if the number of iterations is too high due to the performance impact it might have.

Option 2 (delete method) internally allocates a new buffer with the specified length and then copies the modified contents of the StringBuilder buffer to the new buffer. This is again a costly operation if the number of iteration is too high.

Option 3 is the best choice as it does not involve any new allocation and garbage collection. The setLength method just resets the internal buffer length variable to 0. The original buffer stays in the memory so new memory allocation is not needed and thus it is the fastest way to clear the StringBuilder.

Checkout other StringBuilder examples. Read this to know how to check if StringBuilder is empty or other String examples to know more.

StringBuilder JavaDoc
StringBuffer JavaDoc