Mechanics of String Concatenation in Java

Compile-Time Constant String Concatenation

When concatenating string literals, the operation is performed during compilation. The Java compiler optimizes these expressions by resolving them before runtime, storing the final result directly in the constant pool. Consider this bytecode representation: Both references point to the same constant pool entry for "abc", making their identity comparison return true.

Runtime String Concatenation with Variables

String concatenation involving at least one variable occurs at runtime and creates a new object in the heap memory. The implementation uses a StringBuilder instance, invoking its append() method for each component before calling toString() to produce the final string. ```java public void analyzeConcatenation() { String first = "hello"; String second = "world"; String combined = first + second; } ``` The corresponding bytecode sequence: ``` 0 ldc #2 2 astore_1 3 ldc #3 5 astore_2 6 new #4 9 dup 10 invokespecial #5 > 13 aload_1 14 invokevirtual #6 17 aload_2 18 invokevirtual #6 21 invokevirtual #7 24 astore_3 25 return ``` Execution breakdown: 1. Load "hello" from constant pool to local variable slot 1 2. Load "world" from constant pool to local variable slot 2 3. Instantiate a new StringBuilder 4. Append first variable via StringBuilder.append() 5. Append second variable via StringBuilder.append() 6. Generate final string through StringBuilder.toString()

Key Implementation Details

StringBuilder's toString() method constructs a new String object from its internal character array. This process doesn't check the string pool first - it directly allocates memory in the heap for the new string. ```java public class StringComparison { public static void main(String[] args) { String literal = "test"; String part1 = "te"; String part2 = "st"; String concatenated = part1 + part2; System.out.println(literal == concatenated); // Prints false } } ``` The comparison fails because literal references a string from the constant pool, while concatenated references a heap-allocated object created at runtime. Despite having identical character sequences, their memory locations differ.

Optimization Considerations

When performing multiple concatenations in a loop, explicitly using StringBuilder is more efficient than repeated + operations, as it prevents unnecessary intermediate object creation. ```java // Inefficient approach String result = ""; for (int i = 0; i < 1000; i++) { result += i; // Creates new StringBuilder each iteration } // Optimized approach StringBuilder builder = new StringBuilder(); for (int i = 0; i < 1000; i++) { builder.append(i); } String result = builder.toString(); ```

Tags: java String Concatenation JVM StringBuilder Bytecode

Posted on Sat, 09 May 2026 04:15:48 +0000 by rudibr