When Does Java Use StringBuilder for String Concatenation? A Deep Dive

This article examines why identical-looking string concatenations in Java sometimes use StringBuilder and other times are optimized away, showing bytecode differences, explaining compiler behavior, and summarizing the conditions that affect reference equality.

Programmer DD
Programmer DD
Programmer DD
When Does Java Use StringBuilder for String Concatenation? A Deep Dive

Introduction

Recently I wondered about Java string concatenation behavior and created a demo to see when the compiler uses StringBuilder and when it optimizes the code.

1. Problem

Case 1

Comparing str == str2 yields false .

Case 2

Here the comparison returns true .

2. Investigation

Why do the results differ? By running javap -c TestDemo.class to decompile the bytecode, the underlying cause becomes clear.

In Case 1 the bytecode shows that Java creates a StringBuilder, appends the strings, and then calls toString(). The resulting object resides at a different memory address from the constant‑pool string "111", so == is false.

In Case 2 the compiler folds the expression "111" + "" into the constant "111" at compile time. Both variables therefore reference the same interned string, making == true.

3. Summary

1. When a variable participates in concatenation, the compiler cannot optimize; it must use StringBuilder, producing a new object whose reference differs from the constant‑pool string.

2. When only constant strings are concatenated, the compiler performs constant‑folding, and the resulting string is taken from the constant pool, so reference equality holds.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JVMCompiler OptimizationstringbuilderString concatenation
Programmer DD
Written by

Programmer DD

A tinkering programmer and author of "Spring Cloud Microservices in Action"

0 followers
Reader feedback

How this landed with the community

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.