Junior — Middle
Can you explain the internal implementation and mechanism of the StringBuilder class in Java?
sobes.tech AI
Answer from AI
The StringBuilder class in Java is implemented as a mutable character buffer. It contains an internal array of char[] that dynamically expands when new characters or strings are added.
Main implementation points:
- Initially, a fixed-size array (usually 16 characters) is allocated.
- When adding characters, if the current array is full, a new larger array (usually 1.5-2 times bigger) is created, and the old data is copied into it.
- Methods like append, insert, and others modify the array's contents without creating new strings, which is much more efficient than string concatenation.
Example:
StringBuilder sb = new StringBuilder();
sb.append("Hello");
sb.append(' ');
sb.append("World");
System.out.println(sb.toString()); // Outputs "Hello World"
Thus, StringBuilder is optimized for frequent string modifications without creating many intermediate objects.