String Methods & StringBuilder in Java
Beyond the basics, String has dozens of useful methods — trim() removes leading and trailing whitespace, split(regex) breaks a string into an array of pieces, replace(old, new) swaps every occurrence of one substring for another — all returning a new String, since String itself never changes in place. That immutability becomes a real performance problem when building up text through many small concatenations in a loop, since each + creates an entirely new String object, discarding the previous one immediately.
StringBuilder solves that by being genuinely mutable — its append() method adds text to the same underlying buffer in place, with no new object created per call. That makes it the standard tool for assembling a string piece by piece before converting the final result back to a String with toString() only once, at the very end.
Common String methods
trim(), split(regex), replace(old, new), and similar all return a new String, since the original is never modified.
Why repeated concatenation is slow
Every + in a loop creates an entirely new String object and discards the previous one, which adds up across many iterations.
StringBuilder is mutable
Its internal buffer grows and changes in place, unlike String.
append()
Adds text, of nearly any type, to the end of the buffer directly, with no new object created per call.
toString() at the end
StringBuilder converts to a regular String only once, when the building process is actually finished.
public class BuilderDemo { public static void main(String[] args) { StringBuilder sb = new StringBuilder(); for (int i = 1; i <= 3; i++) { sb.append("Item ").append(i).append(" "); } String result = sb.toString().trim(); System.out.println(result); }}The quadratic cost of repeated String concatenation comes from re-copying all previously accumulated characters into a new String on every single +=. StringBuilder avoids that by growing its own buffer in place instead.
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in Java yourself — building beats watching.