Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

A Better StringBuilder

DZone's Guide to

A Better StringBuilder

· Java Zone
Free Resource

Just released, a free O’Reilly book on Reactive Microsystems: The Evolution of Microservices at Scale. Brought to you in partnership with Lightbend.

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).

Strategies and techniques for building scalable and resilient microservices to refactor a monolithic application step-by-step, a free O'Reilly book. Brought to you in partnership with Lightbend.

Topics:

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}