BackendBench
Coffee

Unravel โ€บ Java concepts โ€บ Strings and text

Java language

StringBuilder and string building

Strings in Java never change.

๐Ÿ”Ž Unravel this example

At a glance

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.

What happens, in order
  1. 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
  2. 2For a single expression such as "Hello " + name + "!" the compiler already does the efficient thing, so + is fine there
  3. 3String.join(", ", list), StringJoiner and Collectors.joining(", ") build separated lists without writing the comma logic yourself
  4. 4insert, reverse, deleteCharAt and setLength modify the buffer; StringBuffer is the older, synchronized version
Remember
Watch out
+= on a String inside a loopSharing one StringBuilder between threadsCalling toString() inside the loop instead of once at the endWriting comma logic by hand when String.join exists
Example (highlighted lines explain it)
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(", "));
  1. line 1 uses StringBuilder, the core of StringBuilder and string building
  2. line 4 uses append, the core of StringBuilder and string building
  3. line 6 uses append, the core of StringBuilder and string building
  4. 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.join exists.

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:

Part of a learning path

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.