Junior — Middle
How is the StringBuilder data structure implemented in Java and how does it work with string mutability?
sobes.tech AI
Answer from AI
In Java, the StringBuilder class implements a mutable sequence of characters, which allows for efficient modification of strings without creating new objects, as is the case with the standard String class.
How it works:
- Inside StringBuilder, there is a character array (char[] buffer).
- When adding or changing content, StringBuilder modifies this array directly if there is enough space.
- If the current buffer is full, it is expanded (the array size is increased), allowing more characters to be added.
This is much more efficient than string concatenation using the + operator, which creates new String objects with each operation.
Example usage:
StringBuilder sb = new StringBuilder("Hello");
sb.append(", world!");
sb.insert(6, " dear");
System.out.println(sb.toString()); // Outputs: Hello dear, world!
Thus, StringBuilder allows modifying a string without creating new objects, improving performance during multiple text modifications.