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: 2020-02-24T12:21:39+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements