Backend Development 9 min read

Understanding Java String Concatenation, StringBuilder, and JVM Object Creation

The article explains why using the '+' operator for string concatenation in Java creates multiple temporary objects, how the StringBuilder class and compiler optimizations like StringConcatFactory reduce memory overhead, and demonstrates object creation counts through interview‑style examples and javap bytecode analysis.

Architect's Guide
Architect's Guide
Architect's Guide
Understanding Java String Concatenation, StringBuilder, and JVM Object Creation

When concatenating strings in Java with the + operator, each iteration creates a new immutable String object, leading to many temporary objects in the string constant pool and increased garbage‑collection pressure. To avoid this, the Java standard library provides StringBuilder , a mutable object that pre‑allocates a buffer so only one object is created for the whole concatenation.

In most cases, explicit use of StringBuilder is unnecessary because the Java compiler rewrites simple + concatenations into calls to StringConcatFactory , which internally uses either array copying or a StringBuilder to perform the operation efficiently.

The article then presents two interview questions to illustrate object creation:

1. String str = "a" + "b"; – the compiler folds the constant expression into "ab" , creating a single string object in the constant pool.

2. String str = new String("a" + "b") + "a" + "b"; – the compiler first creates the constant "ab" in the pool, then a new String object on the heap, followed by a StringBuilder that appends the literals and finally produces the result "abab" . This sequence creates three string objects and one StringBuilder object.

Bytecode analysis using javac -g cp1.java and javap -v cp1 confirms these object creations. The constant pool shows an entry for "ab" , and the method main contains instructions that instantiate a StringBuilder , invoke append , and call toString to obtain the final string.

Overall, the article demonstrates how Java’s compilation and runtime mechanisms affect memory usage during string concatenation and why understanding StringBuilder and compiler optimizations is essential for writing performant backend code.

JavaJVMPerformanceStringBuilderString Concatenation
Architect's Guide
Written by

Architect's Guide

Dedicated to sharing programmer-architect skills—Java backend, system, microservice, and distributed architectures—to help you become a senior architect.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.