String Concatenation in Java

Naveen AnamaneniUpdated · 5 min read

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

Concat.java▶ Try it
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);
    }
}
Output
Navika Anamaneni
Navika Anamaneni
Navika Anamaneni
Navika Anamaneni
WayBest for
a + bEveryday 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.appendBuilding 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:

Order.java▶ Try it
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);
    }
}
Output
Total: 1020
Total: 30
30 items
131!
City: null

How it works

  1. "Total: " + 10 happens first and gives the string "Total: 10". Then + 20 joins again: "Total: 1020".
  2. Brackets make the addition happen first: (10 + 20) is 30.
  3. 10 + 20 are both numbers, so they're added before the string arrives: "30 items".
  4. 'A' + 'B' are both char, which are numbers underneath (65 + 66), so they're added to 131 before joining with "!".
  5. Joining null gives the text "null"; it doesn't throw.

Why + in a Loop Is Slow

+ copies everything each time; StringBuilder appends in place

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.

Speed.java▶ Try it
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());
    }
}
Output
50000 50000

Both 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

  1. Easy: Predict, then check: 1 + 2 + "3" + 4 + 5.
  2. Harder: Build the string "1, 2, 3, ..., 100" (numbers separated by comma and space, with no trailing comma) using StringBuilder, and again using String.join with a list.

Quick check: Concatenation

4 questions
1What does "Total: " + 10 + 20 print?
2What does 10 + 20 + " items" print?
3Why is += in a long loop slow?
4What does "City: " + null produce?

Key Takeaways

Was this tutorial helpful?

Lesson 192 of 482