How Java do the string concatenation using "+"?

java, string

Solution

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("a");
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'sfurther explanation on the topic.

And more StackOVerflow questions on the issue:

Is it better to reuse a StringBuilder in a loop?

What's the best way to build a string of delimited items in Java?

StringBuilder vs String concatenation in toString() in Java

Problem

I read about the way Java works with `+=` operator, using `StringBuilder`. Is it the same with a `("a" + "b")` operation?

Original source

Related problems