Sobes.tech
Junior

Do you know the difference between StringBuilder and string concatenation in Java?

sobes.tech AI

Answer from AI

StringBuilder is used for efficient modification of strings within the same object, saving memory during multiple changes. String concatenation with the + operator creates a new string at each step, which can be slower and consume more memory when working with many modifications.

Example of StringBuilder:

// Using StringBuilder for efficient concatenation
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 1000; i++) {
    sb.append("String " + i);
}
String result = sb.toString();

Example of concatenation with the + operator:

// Using concatenation with the + operator (less efficient for multiple operations)
String result = "";
for (int i = 0; i < 1000; i++) {
    result += "String " + i; // Each operation creates a new string
}

Main differences:

Characteristic StringBuilder Concatenation with + operator
Efficiency High for multiple modifications Low for multiple modifications
Memory consumption Economical Higher
Object creation Modifies existing object Creates a new object at each step