String Concatenation in Java
Concatenation means joining pieces of text end to end: a first name, a space and a surname become a full name. Java gives you several ways to do it. The + operator is the one you'll use most, and it's perfectly fine for everyday code. But it has two surprises: it reads left to right, which can turn numbers into text earlier than you expect, and it gets slow inside loops. Both are easy to avoid once you see why they happen.
Four Ways to Join Text
public class Concat {
public static void main(String[] args) {
String first = "Navika";
String last = "Anamaneni";
System.out.println(first + " " + last);
System.out.println(first.concat(" ").concat(last));
System.out.println(String.join(" ", first, last));
StringBuilder sb = new StringBuilder();
sb.append(first).append(' ').append(last);
System.out.println(sb);
}
}Navika Anamaneni
Navika Anamaneni
Navika Anamaneni
Navika Anamaneni| Way | Best for |
|---|---|
a + b | Everyday joining of a few pieces, including numbers |
a.concat(b) | Rarely used; works only with strings and fails on null |
String.join(", ", parts...) | Joining many pieces with the same separator |
StringBuilder.append | Building text in a loop or in many steps |
Left to Right: The Number Trap
+ means addition between two numbers and joining as soon as one side is a string. Java evaluates it from left to right, one pair at a time:
public class Order {
public static void main(String[] args) {
System.out.println("Total: " + 10 + 20);
System.out.println("Total: " + (10 + 20));
System.out.println(10 + 20 + " items");
System.out.println('A' + 'B' + "!");
String missing = null;
System.out.println("City: " + missing);
}
}Total: 1020
Total: 30
30 items
131!
City: nullHow it works
"Total: " + 10happens first and gives the string"Total: 10". Then+ 20joins again:"Total: 1020".- Brackets make the addition happen first:
(10 + 20)is30. 10 + 20are both numbers, so they're added before the string arrives:"30 items".'A' + 'B'are bothchar, which are numbers underneath (65 + 66), so they're added to131before joining with"!".- Joining
nullgives the text"null"; it doesn't throw.
Why + in a Loop Is Slow
Strings can't change, so s += "x" can't add to s. It creates a new string and copies all the old characters into it, plus one more. For 50,000 steps, that's 50,000 new strings and more than a billion characters copied in total. StringBuilder keeps one growing buffer and adds to its end.
public class Speed {
public static void main(String[] args) {
int n = 50_000;
String s = "";
for (int i = 0; i < n; i++) {
s += "x";
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++) {
sb.append("x");
}
System.out.println(s.length() + " " + sb.length());
}
}50000 50000Both give the same result. When we timed it on a laptop, the += loop took about 70 to 100 ms and the StringBuilder loop took under 1 ms. The gap grows much faster than n: doubling the loop roughly quadruples the += time.
Common Mistakes
"Sum: " + a + b for arithmetic. Wrap it: "Sum: " + (a + b).
+= on a String inside a big loop. Use StringBuilder.
Calling concat on a variable that might be null. It throws; + prints "null" instead.
Under the Hood
Since Java 9, javac compiles a one-line a + " " + b into a single invokedynamic call to makeConcatWithConstants, which works out the final length once and copies each piece once. So a single expression is efficient. The loop is slow because each pass is a separate expression that builds a whole new string.
Joining constants costs nothing at runtime: "Nav" + "ika" is turned into "Navika" by the compiler, so it even shares the pooled literal.
Interview Corner
Why is string concatenation in a loop slow?
Strings are immutable, so each s += x creates a new String and copies all existing characters into it. Over n iterations that copies about n squared over 2 characters and creates n temporary objects. StringBuilder appends into one resizable buffer, so the total work grows only linearly.
What does "Total: " + 10 + 20 print?
"Total: 1020". The + operator is evaluated left to right; "Total: " + 10 produces a string, so + 20 is also string concatenation. Use brackets, "Total: " + (10 + 20), to add first.
Practice
- Easy: Predict, then check:
1 + 2 + "3" + 4 + 5. - Harder: Build the string
"1, 2, 3, ..., 100"(numbers separated by comma and space, with no trailing comma) usingStringBuilder, and again usingString.joinwith a list.
Key Takeaways
Was this tutorial helpful?