Tom Brito Tom Brito - 6 months ago 46
Java Question

How Java do the string concatenation using "+"?

I read about the way Java works with

operator, using

Is it the same with a
("a" + "b")


No. It's not the same using StringBuilder than doing "a" + "b".

In Java, String instances are immutable.

So, if you do:

String c = "a" + "b";

You are creating new Strings every time you concatenate.

On the other hand, StringBuilder is like a buffer that can grow as it needs when appending new Strings.

StringBuilder c = new StringBuilder();
c.append("b"); // c is only created once and appended "a" and "b".

Rule of the thumb is (changed thanks to the comments I got):

If you are going to concatenate a lot (i.e., concatenate inside a loop, or generating a big XML formed by several string concatenated variables), do use StringBuilder. Otherwise, simple concatenation (using + operator) will be just fine.

Compiler optimizations also play a huge role when compiling this kind of code.

Here's further explanation on the topic. And more StackOVerflow questions on the issue:

One, Two, Three.