DEV Community

Adetayo Akinsanya
Adetayo Akinsanya

Posted on Originally published at unkletayo.dev on

Strings: building, joining, and formatting

Strings: building, joining, and formatting

String concatenation with + is fine for joining two or three values. In a loop, it becomes expensive quickly. Here is why.

String report = "";
for (String line : lines) {
    report = report + line + "\n";
}

Enter fullscreen mode Exit fullscreen mode

Each iteration creates a new String object from the entire accumulated text so far, plus one more line. After the first iteration, report holds one line. After the second, two. The JVM allocated a fresh string for each step. For a list of n lines of average length L, the total bytes allocated across all iterations are L × (1 + 2 + 3 + ... + n) = L × n(n+1)/2. That grows with the square of the input size.

This article covers when + is appropriate, what to use instead when it is not, and how to choose among StringBuilder, StringBuffer, StringJoiner, and formatted().

How + works

The + operator on strings is not a built-in JVM instruction. The compiler translates it. Since Java 9 (JEP 280), the translation uses an invokedynamic instruction that calls StringConcatFactory.makeConcatWithConstants() at runtime. The runtime can choose the concatenation strategy; the common path allocates a single internal buffer for each + expression and produces one result string.

For a single concatenation expression, one call site, that one-buffer-one-result behavior is fine.

String greeting = "Hello, " + name + "!"; // one expression, one result

Enter fullscreen mode Exit fullscreen mode

The expensive case is a loop where each iteration assigns the full result back to an accumulator. Each assignment creates a new string containing the entire accumulated text, so the next iteration must copy all of it again, plus one more element.

for (String item : items) {
    result = result + item + ", "; // full copy every iteration
}

Enter fullscreen mode Exit fullscreen mode

The fix is a mutable buffer that accumulates content without copying, then produces one string at the end.

StringBuilder

StringBuilder builds a string by accumulating content in a mutable internal buffer, then producing the final String with a single toString() call.

StringBuilder sb = new StringBuilder();
for (String line : lines) {
    sb.append(line).append('\n');
}
String report = sb.toString();

Enter fullscreen mode Exit fullscreen mode

The JVM allocates the buffer once, with an initial capacity of 16 characters. When the content exceeds the capacity, it expands to (oldCapacity + 1) × 2, which is 34 for the initial 16-character buffer. The final toString() allocates exactly one String of the right size. Total allocations: one buffer (possibly reallocated a handful of times), one result string, constant regardless of input size.

If you know the expected length in advance, pass it to the constructor:

int estimated = lines.size() * 80;
StringBuilder sb = new StringBuilder(estimated);

Enter fullscreen mode Exit fullscreen mode

This eliminates reallocations. The estimate does not need to be exact; it just prevents the repeated doubling that happens with large inputs and a 16-character starting capacity.

The methods you reach for most are append(), insert(int offset, String str), delete(int start, int end), deleteCharAt(int index), reverse(), charAt(int index), setCharAt(int index, char ch), indexOf(String str), substring(int start, int end), and toString(). Most mutating methods return this, so appends can chain:

sb.append("Account ").append(id).append(": ").append(balance);

Enter fullscreen mode Exit fullscreen mode

One thing worth knowing: sb.toString() creates a new String from the buffer contents but does not reset the builder. Calling toString() twice gives two separate String objects with equal content. If you need to reuse the builder, call sb.setLength(0) to clear it.

StringBuilder is not thread-safe. That is deliberate. Its single-threaded use case does not need synchronization.

StringBuffer

StringBuffer has the same API as StringBuilder. Every method is synchronized.

If two threads must append to the same builder simultaneously, StringBuffer prevents data races. In practice this scenario is unusual in well-structured code. Strings passed between threads are usually immutable String objects, not shared mutable builders.

For single-threaded code, prefer StringBuilder. Its methods are identical, without the synchronization cost.

StringBuffer predates StringBuilder by several Java versions. StringBuilder was added in Java 5 specifically for single-threaded use. New code rarely needs StringBuffer.

StringJoiner

StringJoiner builds a delimiter-separated sequence, with optional prefix and suffix.

StringJoiner sj = new StringJoiner(", ");
sj.add("Alice").add("Bob").add("Carol");
System.out.println(sj); // Alice, Bob, Carol

Enter fullscreen mode Exit fullscreen mode

With a prefix and suffix:

StringJoiner sj = new StringJoiner(", ", "[", "]");
sj.add("Alice").add("Bob");
System.out.println(sj); // [Alice, Bob]

Enter fullscreen mode Exit fullscreen mode

Before any element is added, toString() returns an empty string, with no prefix, no suffix, and no delimiter. Use setEmptyValue() if you need a different result for the empty case:

StringJoiner sj = new StringJoiner(", ", "[", "]");
sj.setEmptyValue("none");
System.out.println(sj); // none
sj.add("A001");
System.out.println(sj); // [A001]

Enter fullscreen mode Exit fullscreen mode

merge(StringJoiner other) appends other's accumulated content, without its prefix and suffix, as a single unit to the current joiner. The API documentation states: "elements from the other StringJoiner are concatenated with that delimiter and the result is appended to this StringJoiner as a single element." So other's internal delimiter is preserved for the transferred content, and the primary joiner's delimiter separates that content from earlier elements.

StringJoiner primary = new StringJoiner(", ", "(", ")");
primary.add("x");

StringJoiner secondary = new StringJoiner("-", "{", "}");
secondary.add("y").add("z");

primary.merge(secondary);
System.out.println(primary); // (x, y-z)

Enter fullscreen mode Exit fullscreen mode

The { and } from secondary do not appear. The y and z were joined using secondary's - delimiter, producing the unit y-z. That unit was appended to primary, which then joins x and y-z with its own , delimiter. If other has no elements, merge() has no effect.

String.join() delegates to StringJoiner internally. When you have a list and want a joined string in one step, String.join() is simpler. When you need to build incrementally, control the prefix and suffix, or compose a stream with Collectors.joining(), use StringJoiner directly.

Common String operations

A reference table of the methods you use most.

Inspection

Method Returns Notes
length() int Character count
isEmpty() boolean True if length is 0
isBlank() boolean True if empty or all Unicode whitespace (Java 11)
charAt(int index) char Throws IndexOutOfBoundsException if out of range
indexOf(String str) int First occurrence, or -1
lastIndexOf(String str) int Last occurrence, or -1
contains(CharSequence s) boolean True if s appears anywhere
startsWith(String prefix) boolean
endsWith(String suffix) boolean

Transformation (all return a new String)

Method Notes
substring(int start) From start to end
substring(int start, int end) From start (inclusive) to end (exclusive)
toLowerCase(Locale locale) Use Locale.ROOT for identifiers and tokens; avoid the no-argument form
toUpperCase(Locale locale) Same; the no-argument form uses the default locale, which varies
strip() Removes leading and trailing Unicode whitespace (Java 11)
stripLeading(), stripTrailing() One side only (Java 11)
trim() Removes characters with code point ≤ 32; predates strip()
replace(CharSequence old, CharSequence new) All literal occurrences
replaceAll(String regex, String replacement) All regex matches
replaceFirst(String regex, String replacement) First match only
repeat(int count) Concatenate n copies (Java 11)
indent(int n) Prepend n spaces to each line, adds trailing newline if absent (Java 12)
stripIndent() Strips common leading whitespace, as a text block does (Java 15)
translateEscapes() Interprets \n, \t, etc., in a string at runtime (Java 15)

Splitting and converting

Method Notes
split(String regex) Returns String[]
split(String regex, int limit) Positive limit: at most that many parts; negative: no limit; zero: trailing empty strings removed
toCharArray() Defensive copy as char[]
getBytes(Charset charset) Encode to bytes; always specify the charset
chars() IntStream of char values (Java 8)

Comparison (use equals() for content, never ==)

Method Notes
equals(Object other) Case-sensitive character comparison
equalsIgnoreCase(String other) Case-insensitive
compareTo(String other) Lexicographic; negative, zero, or positive
compareToIgnoreCase(String other)

Choosing the right tool

Different scenarios, different tools.

If you are joining two or three values in a single expression, + is fine. The compiler translates it to a single-call operation.

If you are accumulating strings across loop iterations or conditionally appending to a buffer, use StringBuilder. Create it once before the loop, append inside, call toString() once at the end.

If you need a delimiter-separated string from a collection, String.join() or Collectors.joining() is cleaner than a manual StringBuilder with delimiter logic.

If you need alignment, padding, or format specifiers, use formatted() or String.format(). For locale-sensitive number formatting, such as a thousand separator or a currency symbol, use String.format(Locale, format, args).

If you need to decode bytes from an external source into a string, use new String(bytes, charset) with an explicit Charset.

If multiple threads must share one mutable builder, use StringBuffer. Reconsider whether the design requires shared mutable state at all before reaching for it.

Prediction exercise

StringJoiner sj = new StringJoiner(", ", "(", ")");
sj.setEmptyValue("empty");

System.out.println(sj);

sj.add("x");
System.out.println(sj);

StringJoiner other = new StringJoiner("-", "{", "}");
other.add("y").add("z");
sj.merge(other);
System.out.println(sj);

Enter fullscreen mode Exit fullscreen mode

Predict each line of output. Then: if other had no elements added to it before the merge, what would the third println show?

Top comments (0)