Java String formatting FAQ: How can I format Java String output?
For a long time I appended Java strings together using the
+ operator to combine them into the output format I wanted, but I always knew that approach was pretty ugly. Fortunately at some point I learned how to use the Java String format method to format my text, and as you’ll see, the resulting code is much cleaner this way.
If you’re familiar with the
sprintf function of other programming languages, the String
format method is basically a “Java sprintf” method. Let’s take a look at a few quick examples.
Here’s a quick example of how to use the
format method to format a string before I pass it to a Log4J
log.debug( String.format("The rename status is (%d)", RENAME_SUCCEEDED) );
If you’re familiar with the sprintf function from other languages like C, Perl, or Ruby, this syntax will look familiar. But, if you’re not familiar with this syntax, what happens in the line of code above is that the
%d in my Java String is replaced by the value of the variable
RENAME_SUCCEEDED, which in this case happens to be a constant in my class. The
%d symbol is a placeholder that indicates that a decimal value (something like an
long in Java) should be printed in place of this symbol. The value of that decimal comes from the variable that follows my string, in this case the
If it helps to see the format method used without the additional
log.debug method, here’s an example where I use the String.format method to assign a similarly formatted String to another String:
String status = String.format("The rename status is (%d)", RENAME_SUCCEEDED);
Finally, here is an example of how to use multiple variables with the String
log.debug( String.format("%s is %d years old, er, young", "Al", 45) );
Note that I keep using the
log.debug method in these examples for a reason, specifically that I want to show this String format method. However, if you’re interested in just printing formatted strings to system output or system error, there are
System.err.format methods that are very similar to the String
format method. Rather than make this tutorial any longer, here’s a link to a Java System.out.format (Java printf) example.
As a final note, if you’re not familiar with the
printf function in other languages, including all the different printf print formatting options you can use, I’ve put together this printf format examples page, with
printf examples shown in several different programming languages.