When Does Java Use StringBuilder for String Concatenation?
This article investigates Java's string concatenation behavior, demonstrating through two examples why some concatenations invoke StringBuilder while others are optimized by the compiler, and explains the underlying bytecode differences revealed by decompiling with javap.
The author noticed inconsistent results when comparing concatenated strings in Java and created two demo cases to explore when the Java compiler uses StringBuilder versus when it optimizes the concatenation.
Case 1 shows a concatenation involving a variable and a literal, resulting in str == str2 being false . The accompanying screenshot (omitted) displays the output and the bytecode, which reveals that the compiler generated a StringBuilder instance and called its toString() method.
Case 2 uses only literals in the expression, yielding str == str2 as true . The screenshot (omitted) shows that the compiled bytecode no longer contains a StringBuilder call; the expression was folded into a single constant string.
To investigate, the author ran javap -c TestDemo.class on the compiled class files. The decompiled bytecode for Case 1 contains instructions that create a StringBuilder , append the variable and the literal, and invoke toString() . In contrast, the bytecode for Case 2 directly loads the constant string from the constant pool, confirming that the compiler performed constant‑folding optimization.
Conclusion : When a concatenation involves a variable, the compiler cannot determine the final value at compile time, so it generates StringBuilder code, leading to distinct objects and a false comparison. When the expression consists solely of compile‑time constants, the compiler folds the expression into a single constant string stored in the constant pool, making both references point to the same object and resulting in a true comparison.
Architect's Tech Stack
Java backend, microservices, distributed systems, containerized programming, and more.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.