tags:

views:

376

answers:

8

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

+8  A: 

No. It's no 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's further explanation on the topic. And more StackOVerflow questions on the issue:

One, Two, Three.

Pablo Santa Cruz
It's not guaranteed that you're creating new Strings every time you concatenate; it's actually up to the compiler. A poor-quality compiler would behave as you describe...
Donal Fellows
Not necessarily. The compiler will optimize it anyway. Change your rule of thumb to: "if you're going to use `stringA += stringB`, then use `StringBuilder` instead, because it would indeed eat heap. Your answer is more implying that you need a `StringBuilder` for every `stringA + stringB`, this is not true.
BalusC
In fact it is required by the JLS that concatenation of compile time constants results in an interned `String`. Rule of thumb should be that if you are going to create a `String` in a loop and there is any chance at all that it'll loop a number of times, the use a `StringBuilder`. No point in complicating linear concatenation code with `StirngBuilder`.
Tom Hawtin - tackline
Not only do String literals concatenated with + get changed to a single string at compile time (in your example, the compiler would simplify it to String c = "ab";), the compiler can also optimize concatenation with + to use a StringBuilder anyway. You should only really need to use StringBuilder for more complex appending, such as when appending in a loop.
ColinD
Agree. With all of you. Just tried to keep it simple. I think the questions asks for general a general answer, an answer including cases where "a" + "b" can also be strA + strB.
Pablo Santa Cruz
@ColinD: It can only "optimize" it within very narrow constraints. For instance, a concatenation loop will result in a new string on every loop; the `StringBuilder` is not used optimally automatically. Of course, it only really matters for very large loops or loops involving very large strings.
T.J. Crowder
@T.J. Crowder Yes, I know it doesn't do good things with loops, which is why I mentioned them as a case for using StringBuilder directly.
ColinD
-1: The more I look at your answer, the more confused I get. The cases for `+` are literal,literal and something with non-literals in. The compiler can (and should) optimize the literals-only case (but doesn't in some cases, which is a compiler-quality issue) and in the other case issues a `StringBuilder` (or `StringBuffer` in early versions of Java) internally. In complex cases (e.g., concat in a loop) it's better to write everything out by hand.
Donal Fellows
(The compiler quality issue is really a failure to take advantage of the associativity of `+` BTW)
Donal Fellows
+5  A: 

Yes, it's the same, but the compiler can additionally optimize concatenations of literals before issuing the code, so "a"+"b" can be just issued as "ab" directly.

Donal Fellows
phoenix24
@phoenix24: Actually, he spouts stupid rubbish **precisely** because he doesn't differentiate between literal concatenation and non-literal concat.
Donal Fellows
A: 

Strings are more commonly concatenated with the + operator, as in "Hello," + " world" + "!"

Source

inkedmn
Yes, but I think he means, how does the compiler do that operation. (And the answer is indeed that it uses a `StringBuilder` under-the-covers.)
T.J. Crowder
A: 

I recommend you to have a look at this excellent article.

Bozhidar Batsov
+1  A: 

If you’re only building long strings, then using StringBuilder is recommended. For shorter strings, with fixed creations (such as res = a + " " + b + " : " + c;) it should be okay. For iterations over a group of values, I’d seriously recommend StringBuilder.

Luis
+8  A: 
T.J. Crowder
people voting seens to agree with the "No" answer..
Tom Brito
@Tom Brito: Actually, based on the question, I'm not sure whether the one-word answer would be "yes" or "no" so I took that out and just explained what goes on. :-)
T.J. Crowder
excellent explaination! thanks
phoenix24
+1  A: 

For concatenating a fixed number of strings in one expression with +, the compiler will produce code using a single StringBuilder.

E.g. the line

String d = a + b + c;

results in the same bytecode as the line

String d = new StringBuilder().append(a).append(b).append(c).toString();

when compiled using the javac compiler. (The Eclipse compiler produces somewhat more optimized code by invoking new StringBuilder(a), thus saving one method call.)

As mentioned in other answers, the compiler will concatenate string literals like "a" + "b" into one string itself, producing bytecode that contains "ab" instead.

As mentioned everywhere on the net, you should not use + to build up one string within a loop, because you are copying the beginning of the string over and over to new strings. In this situation you should use one StringBuilder which you declare outside the loop.

Christian Semrau
A: 

"a" + "b" operation

Though readable, easy to format and straight forward, concatenating strings with "+" is considered to be bad in Java.

Each time you append something via '+' (String.concat()) a new String is created, the old String content is copied, the new content is appended, and the old String is discarded. The bigger the String gets the longer it takes - there is more to copy and more garbage is produced. Note: if you are just concatenating a few (say 3,4) strings and not building a string via a loop or just writing some test application, you could still stick with "+"

Using StringBuilder

When performing extensive String manipulation (or appending through a loop), replacing "+" with StringBuilder.append is likely recommended. The intermediate objects mentioned in case of "+" are not created during append() method call.

Also to be noted that optimizations in the Sun Java compiler, which automatically creates StringBuilders (StringBuffers < 5.0) when it sees String concatenations. But that is just Sun Java compiler.

ring bearer