Java Notes
StringBuilder is a mutable sequence of characters for efficiently building or editing text, especially inside loops in a single-threaded program.
StringBuilder holds editable text. Use it when a program repeatedly adds, removes, or changes text. Unlike String, its methods change the same object and then return that object for further work.
Build text in a loop
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
Every append() adds to the existing builder. With String, repeated + inside this loop would repeatedly create temporary values. Use StringBuilder for generated reports, CSV lines, HTML fragments, or any text assembled in many steps.
Edit the characters already present
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
insert(position, value) adds characters. replace(start, end, value) replaces the range from start up to but not including end. delete(start, end) removes that range. Check indexes carefully: an invalid index throws StringIndexOutOfBoundsException.
Turn it back into String
Use toString() when you have finished constructing the text and need a normal immutable String.
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
Use StringBuilder in ordinary single-threaded code. If one mutable buffer is deliberately shared by multiple threads, use StringBuffer, whose operations are synchronised.
Continue the lesson path