How can I clear or empty a StringBuilder in Java.

Java 8Object Oriented ProgrammingProgramming

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
raja
Published on 06-Feb-2018 16:29:43
Advertisements