Junior — Middle
Why does using StringBuilder not create redundant string objects in memory?
sobes.tech AI
Answer from AI
StringBuilder in Java uses an internal mutable array of characters (char[]), which expands as needed. Unlike regular strings (String), which are immutable and create a new object with each concatenation, StringBuilder modifies the contents of this array without creating new string objects.
This means that when appending strings sequentially using the append() method, many intermediate String objects are not created, significantly reducing garbage collection load and saving memory.
Example:
StringBuilder sb = new StringBuilder();
sb.append("Hello");
sb.append(" World");
String result = sb.toString();
Here, only one StringBuilder is created, and at the end, one final string, not several intermediate strings.