Java ‘printf’ - formatting output with System.out.format

In my previous tutorial on using the Java String format method ("Java sprintf") I showed how to use the format method of the Java String class to format strings and text output. That method works fine in many situations where you use the sprintf function in other languages, such as when you need to either concatenate strings, or print formatted output using something like Log4J.

However, if you want to print formatted text output using the System.out.println or System.err.println methods with the printf formatting options you're used to with other languages, the easiest way to do that is to instead use the newer System.out.format or System.err.format methods.

Java printf formatting with System.out.format

For instance, here’s the usual “Hello, world” example, using these new Java formatting and printing methods:

System.out.format("%s, %s", "Hello", "world");

While that example hardly makes it look very valuable, here’s a better Java printf-style formatting example that shows the power of these formatting methods:

System.out.format("The '%s' method died at line %d at '%s'.", methodName, lineNumber, currentTime);

To get the same output without using the new Java format method, you’d have to concatenate (merge) your Strings and variables together, which would be some ugly code, something like this:

System.out.println("The '" + methodName + "' method died at line " + lineNumber + " at '" + currentTime + "'.");

(If you’re familiar with the printf or springtf syntax from the C programming language, or similar methods in the Perl or Ruby languages, you’ll instantly be familiar with the syntax used with String.format.)

I find the approach using the format method much easier to write, read, and maintain.

So, as a quick summary, whenever you’re tempted to use those old System.out.println or System.err.println methods, and you need some nice, formatted output, consider using the newer System.out.format or System.err.format methods instead.

printf formatting reference

If you’d like to see much more information about formatting options you can use with the Java System.out.format() method, check out my printf formatting examples (cheat sheet) page. It’s full of printf formatting options that you can use in the Java language (and other languages, like C, Perl, and Ruby).