How Can I Clear or Empty a StringBuilder


You can use Java’s StringBuilder to create and manipulate Strings as follows:

StringBuilder sb = new StringBuilder();
sb.append("Some").append(" ").append("String");
System.out.println(sb.toString());

// "Some String"

The following three (3) options allow you to clear or empty a StringBuilder.

Option 1 – using setLength

sb.setLength(0);

Option 2 – reinstantiating

sb = new StringBuilder();

Option 3 – using delete

sb.delete(0, sb.length());