Unravel โบ Java concepts โบ Strings and text
StringBuilder and string building
Strings in Java never change.
At a glance
Writing a letter on a whiteboard you can add to, instead of recopying the whole letter on a fresh page every time you add a word.
- 1StringBuilder sb = new StringBuilder(); sb.append("a").append(1).append('c'); String s = sb.toString(); appends in place and returns itself so calls can be chained
- 2For a single expression such as "Hello " + name + "!" the compiler already does the efficient thing, so + is fine there
- 3String.join(", ", list), StringJoiner and Collectors.joining(", ") build separated lists without writing the comma logic yourself
- 4insert, reverse, deleteCharAt and setLength modify the buffer; StringBuffer is the older, synchronized version
- The cost of s += x in a loop grows with the square of the number of iterations, because every step copies everything built so far
- A StringBuilder is not thread safe
- A StringBuilder holds a byte or char array larger than its content and a length
StringBuilder sb = new StringBuilder();for (Order o : orders) { if (sb.length() > 0) { sb.append(", "); } sb.append(o.getId());}String ids = sb.toString();String same = orders.stream().map(o -> String.valueOf(o.getId())).collect(Collectors.joining(", "));- line 1 uses StringBuilder, the core of StringBuilder and string building
- line 4 uses append, the core of StringBuilder and string building
- line 6 uses append, the core of StringBuilder and string building
- line 9 uses joining, the core of StringBuilder and string building
Read the full explanation (about 2 min)
Strings in Java never change. Joining many pieces with + in a loop creates a new string each time. StringBuilder collects the pieces in one growing buffer and builds the final string once.
A mental model
Writing a letter on a whiteboard you can add to, instead of recopying the whole letter on a fresh page every time you add a word.
How it works
StringBuilder sb = new StringBuilder(); sb.append("a").append(1).append('c'); String s = sb.toString(); appends in place and returns itself so calls can be chained.
For a single expression such as "Hello " + name + "!" the compiler already does the efficient thing, so + is fine there.
String.join(", ", list), StringJoiner and Collectors.joining(", ") build separated lists without writing the comma logic yourself.
insert, reverse, deleteCharAt and setLength modify the buffer; StringBuffer is the older, synchronized version.
Going deeper
The cost of s += x in a loop grows with the square of the number of iterations, because every step copies everything built so far. It is invisible with ten items and painful with a hundred thousand.
A StringBuilder is not thread safe. If several threads must write to one buffer, give each its own and combine the results, or use a lock.
Strings that hold secrets stay in memory until the garbage collector runs. For passwords prefer char[] that you can overwrite.
Pre-size with new StringBuilder(expectedLength) when you know roughly how big it gets, to avoid repeated growing.
Under the hood
A StringBuilder holds a byte or char array larger than its content and a length. append copies into the spare room and, when full, allocates a bigger array (about double) and copies once. Compact strings store Latin-1 text one byte per character.
Common mistakes
+=on a String inside a loop.- Sharing one StringBuilder between threads.
- Calling
toString()inside the loop instead of once at the end. - Writing comma logic by hand when
String.joinexists.
How Unravel recognises it
When you paste code, Unravel looks for these signs of stringbuilder and string building. Spotting them yourself is a good habit when you read unfamiliar code:
- Types:
StringBuilderStringBufferStringJoiner - Method calls:
append()Collectors.joining()String.join()
Part of a learning path
- Modern Java: lambdas and streams ยท previous: Optional and null safety ยท next: Regular expressions
Related concepts
Frequently asked questions
What is StringBuilder and string building?
Strings in Java never change. Joining many pieces with + in a loop creates a new string each time. StringBuilder collects the pieces in one growing buffer and builds the final string once.
What are the most common mistakes with StringBuilder and string building?
+= on a String inside a loop. Sharing one StringBuilder between threads. Calling toString() inside the loop instead of once at the end. Writing comma logic by hand when String.join exists.
How can I see StringBuilder and string building in real code?
Paste your own Java into Unravel and it will point out where stringbuilder and string building appears, explain how it works at the detail level you choose, and draw the flow of the code around it.