Two ways that work:
- Use
stringBuilderObj.setLength(0). - Allocate a new one with
new StringBuilder()instead of clearing the buffer. Note that for performance-critical code paths, this approach can be significantly slower than thesetLength-based approach (since a new object with a new buffer needs to be allocated, the old object becomes eligible for GC etc).