9

I've heard that the compiler (or was it the JVM?) will automatically use a StringBuilder for some string concatenation. When is the right time to explicitly declare one? I don't need a StringBuffer for being thread-safe.

Thanks.

3
  • 1
    possible duplicate of What happens when Java Compiler sees many String concatenations in one line? Commented Nov 23, 2010 at 23:37
  • 1
    Note: one situation where its won't use a StringBuilder is when the string can be concatenated at Compile time. In which case it just produces one lone string (no StringBuilder) Commented Nov 24, 2010 at 9:28
  • BTW: If you ever need to use StringBuffer for thread safety, you have a design issue IMHO. :P Commented Nov 24, 2010 at 9:28

1 Answer 1

15

The compiler will use it automatically for any string concatenation using "+".

You'd usually use it explicitly if you wanted to concatenate in a loop. For example:

StringBuilder builder = new StringBuilder();
for (String name : names)
{
    builder.append(name);
    builder.append(", ");
}
if (builder.length() > 0)
{
    builder.setLength(builder.length() - 2);
}
System.out.println("Names: " + builder);

Another situation would be where you wanted to build up a string over multiple methods, or possibly conditionalise some bits of the building. Basically, if you're not building the string in a single statement (where the compiler can help you) you should at least consider using StringBuilder.

Sign up to request clarification or add additional context in comments.

9 Comments

I think it's worth mentioning that StringBuilder will not be used in cases like this: String str = ""; str += <something that isn't a compile-time constant>.
Ah that makes sense, thanks! BTW I thought you were a C# guy ;o)
@Jon: C# is certainly my preferred language - but I've written more professional code in Java than C# :)
@Matt: Please give a fuller example. I've just tried it, and it does use StringBuilder with the compiler I'm using (JDK 7). In theory it could use String.concat instead, but I haven't seen any evidence of that happening. Of course, the exact implementation isn't specified, but I can't remember seeing any compiler use String.concat.
@Jon: sorry, I realized that comment was less-than-clear. This answer illustrates what I meant (read: failed) to say. StringBuilder will be used, but in the concatenation in my first comment, it would produce bytecode equivalent to new StringBuilder().append("foo").append(<something that...>).toString();. Bah, I should have initialized str to a non-empty string in that comment, too.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.