How can I clear or empty a StringBuilder in Java.


You can either setLength to be 0 or create a new StringBuilder() instance. See the example below −

Example

public class Tester {
   public static void main(String[] args) {
      StringBuilder builder = new StringBuilder();
      builder.append("sample");
      System.out.println(builder.toString());
      builder.setLength(0);
      System.out.println(builder.toString());
      builder.append("sample");
      System.out.println(builder.toString());
   }
}

Output

sample
sample

Updated on: 24-Feb-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements