Over a million developers have joined DZone.
Silver Partner

A Better StringBuilder

· Java Zone

The Java Zone is brought to you in partnership with DCHQ.  Discover how to deploy & monitor multi-tier Java applications on any cloud in seconds.

Almost noone likes using string "+" for complex text creation. Long chains of .append with StringBuilder also look ugly. So, often one will see something like the following:
StringBuilder builder = new StringBuilder();
builder.append("Hello, world\n")
if (name != null) {
    builder.append(String.format("My name is %s\n", name));
} else {
    builder.append(String.format("Please email me at %s\n", email);
}
doUse(builder.toString();
But does anyone think that this code is almost as bad in performance as str += name? String.format call creates a new StringBuilder, new Formater, then creates String out of this thing and then appends String to your builder. Consider a better way:
Formatter formatter = new Formatter();
formatter.format("Hello, world\n");
if (name != null) {
    formatter.format("My name is %s\n", name);
} else {
    formatter.format("Please email me at %s\n", email);
}
doUse(formatter.toString();
This code has less boilerplate and creates less objects. The only thing you should watch for is if in formatter.format(str) str contains '%' character. But you can always use formatter.format("%s", str) or formatter.out().append(str).

The Java Zone is brought to you in partnership with DCHQ. Learn more about best practices for automating the deployment and management of your Java application on any cloud.

Topics:

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}