Junior — Middle
Explain the internal structure and working mechanism of the StringBuilder class in Java.
sobes.tech AI
Answer from AI
The StringBuilder class in Java is designed for efficient construction and modification of strings without creating new objects for each operation, unlike String.
Internal structure:
- StringBuilder contains a character array
char[] valuethat stores the current characters. - Initially, the array has a certain size (e.g., 16 characters), which increases as needed.
- There is a field
int countorint lengthindicating the current length of the string in the array.
Working mechanism:
- When adding characters or strings (for example, using the
appendmethod), characters are copied into thevaluearray starting from thecountposition. - If the array size is insufficient, the array is expanded: a new array of larger size (usually twice as large) is created, and old characters are copied into it.
- The
toString()methods create a new String object based on the contents of thevaluearray.
Example:
StringBuilder sb = new StringBuilder();
sb.append("Hello");
sb.append(' ');
sb.append("World");
System.out.println(sb.toString()); // Outputs "Hello World"
Thus, StringBuilder optimizes string operations by reducing the number of objects created and increasing performance during multiple string modifications.