I ran across a bug in some code today where a developer had set up a template string similar to the following:


Subsequently they had used a series of replace commands to fill in the values.

String.replace("{1}", "foo");
String.replace("{2}", "bar");
String.replace("{3}", "baz");

It seems that this code is sub-optimal for two reasons. First, it’s not good from a performance point of view, and secondly, it could fail if the first string replace inserted {2} into the string. This would cause the second replace to do two substitutions which may or may not be desired.

I didn’t delve too deeply into the reasons for this, but the debugger showed this code as outputting a string which looked like: “foobarbaz{1}:{2}/{3}” which was the source of the bug. I went hunting for better solutions.

Knowing that Java 1.5 has had printf() functionality similar to C added to it, I wondered if there was an equivalent of sprintf(). It turns out that there is – it is a static method on String called String.format() (javadoc linked). This is a tremendously powerful tool in C, but the java version also allows more sophisticated options like pulling various components of date objects out. The full range of possibilities are documented here.

The new code looks much cleaner IMHO:

String.format("%s:%s/%s", "foo", "bar", "baz");

You should also note that printf() itself is now available on PrintWriter objects such as System.out.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s