Sobes.tech
Junior — Middle

Explain what the StringBuilder class is and when it should be used for string operations in Java.

sobes.tech AI

Answer from AI

The StringBuilder class in Java is used for efficient construction and modification of strings. Unlike regular strings (String), which are immutable, StringBuilder allows changing the content without creating new objects.

Use StringBuilder when you need to modify a string multiple times, such as in loops or when concatenating a large number of parts, to avoid the overhead of creating many temporary strings.

Example:

StringBuilder sb = new StringBuilder();
for (int i = 0; i < 5; i++) {
    sb.append(i).append(", ");
}
String result = sb.toString();
System.out.println(result); // 0, 1, 2, 3, 4,