Sobes.tech
Junior — Middle

What are the differences between the String and StringBuilder classes in Java, and in which cases is it preferable to use each of them?

sobes.tech AI

Answer from AI

In Java, the String class represents an immutable string. Every time the string is modified, a new object is created, which can be inefficient for multiple concatenation operations.

StringBuilder is a mutable character buffer that allows efficient modification of the string without creating new objects.

When to use:

  • String — when the string does not change after creation or changes are minimal.
  • StringBuilder — for frequent modifications of the string, such as in loops or when building large strings.

Example:

StringBuilder sb = new StringBuilder();
for (int i = 0; i < 10; i++) {
    sb.append(i).append(", ");
}
String result = sb.toString();