String Concatenation
In short: Joining several strings (or strings with other values) into a single string with +.
In more detail: When concatenating with +, a non-String value is automatically converted into text via toString(): "Age: " + 25 produces "Age: 25". For very many concatenations (e.g. in a loop), StringBuilder is more efficient, since String in Java is immutable and + creates a completely new string object at every step.
In Depth
String name = "Anna";
int age = 25;
String sentence = "Hello " + name + ", you are " + age + " years old.";
// Inefficient in a loop - creates a new string object on every iteration:
String result = "";
for (int i = 0; i < 1000; i++) {
result += i + ",";
}
// More efficient: ONE mutable buffer instead of 1000 new string objects
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 1000; i++) {
sb.append(i).append(",");
}
String better = sb.toString();Since strings in Java are immutable, every + concatenation creates a completely new string object in memory — for a single concatenation like in the first example, this doesn’t matter, but for thousands of repetitions in a loop, it can noticeably cost performance and memory, since every intermediate result is immediately discarded again. StringBuilder (or the thread-safe variant StringBuffer) avoids this by internally managing a mutable character array, to which .append() appends without creating a new object at every step — only .toString() at the end produces the final, immutable String.
The + operator itself, by the way, is already automatically translated by the compiler into StringBuilder calls when the concatenation sits in ONE expression ("a" + "b" + "c") — the performance problem only occurs when the concatenation is spread across several separate statements/loop iterations, because then a completely new StringBuilder is created and immediately discarded again on every iteration.
See also: Strings, Numbers & Strings