Clear a StringBuilder (or StringBuffer) in Java
This post will discuss how to clear a StringBuilder or StringBuffer in Java.
1. Using setLength() method
A simple solution to clear a StringBuilder/StringBuffer in Java is calling the setLength(0) method on its instance, which causes its length to change to 0. The setLength() method fills the array used for character storage with zeros and sets the count of characters used to the given length.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
import java.util.Arrays; import java.util.List; class Main { public static void main(String[] args) { List<String> words = Arrays.asList("I", "Love", "Java"); StringBuilder sb = new StringBuilder(); for (String word: words) { sb.append(word).append(" "); } System.out.println(sb); sb.setLength(0); for (String word: words) { sb.append(word.toUpperCase()).append(" "); } System.out.println(sb); } } |
Output:
I Love Java
I LOVE JAVA
2. Using delete() method
Another solution to remove all characters from the StringBuilder/StringBuffer instance is to call the delete() method for range 0 till its length.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
import java.util.Arrays; import java.util.List; class Main { public static void main(String[] args) { List<String> words = Arrays.asList("I", "Love", "Java"); StringBuilder sb = new StringBuilder(); for (String word: words) { sb.append(word).append(" "); } System.out.println(sb); sb.delete(0, sb.length()); for (String word: words) { sb.append(word.toUpperCase()).append(" "); } System.out.println(sb); } } |
Output:
I Love Java
I LOVE JAVA
3. Allocate new instance
Instead of clearing the buffer, you can allocate a new instance of StringBuilder/StringBuffer and let GC do its job. However, repeatedly allocating a new buffer can be more costly than clearing the buffer.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
import java.util.Arrays; import java.util.List; class Main { public static void main(String[] args) { List<String> words = Arrays.asList("I", "Love", "Java"); StringBuilder sb = new StringBuilder(); for (String word: words) { sb.append(word).append(" "); } System.out.println(sb); sb = new StringBuilder(); for (String word: words) { sb.append(word.toUpperCase()).append(" "); } System.out.println(sb); } } |
Output:
I Love Java
I LOVE JAVA
That’s all about clearing a StringBuilder/StringBuffer in Java.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)