setLength method is the best choice as it does not involve any new allocation and garbage collection. The setLength method just resets the internal buffer length variable to 0. The original buffer stays in the memory so new memory allocation is not needed and thus it is the fastest way to clear the StringBuilder.
Syntax:
public void setLength(int newLength)
For clearing the contents of the StringBuilder, we are going to pass 0 as a new length as shown in the below example.
Example:
public class JavaStringBufferClearEmptyExample {
public static void main(String[] args) {
StringBuilder sbStr = new StringBuilder();
String strDays[] = {"Sun", "Mon", "Tuesday", "Wed"};
for(int i = 0; i < strDays.length; i++){
//empty StringBuilder
sbStr.setLength(0);
sbStr.append(strDays[i]);
System.out.println(sbStr);
}
}
}
Output:
Sun
Mon
Tuesday
Wed