StringBuilder vs String concatenation in toString() in Java

Given the 2 toString() implementations below, which one is preferred: public String toString(){ return “{a:”+ a + “, b:” + b + “, c: ” + c +”}”; } or public String toString(){ StringBuilder sb = new StringBuilder(100); return sb.append(“{a:”).append(a) .append(“, b:”).append(b) .append(“, c:”).append(c) .append(“}”) .toString(); } ? More importantly, given we have only 3 … Read more

How can I clear or empty a StringBuilder?

How can I clear or empty a StringBuilder? – Read For Learn Skip to content 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 the setLength-based approach (since a new object with a new buffer needs to be … Read more