Java String formatting FAQ: How can I format Java String output?
Java String formatting solution
One way to format Java string output is with the format
method of the String
class, which works like a “Java sprintf
” method. Here are some examples:
// output a string log.debug( String.format("The rename status is (%d)", RENAME_SUCCEEDED) ); // format some text and assign it to a string String status = String.format("The rename status is (%d)", RENAME_SUCCEEDED); // format a string with multiple variables (interpolation) log.debug( String.format("%s is %d years old, er, young", "Al", 45) );
For more information on those examples, see the sections below.
A String.format example
Here’s a quick example of how to use the String.format
method to format a string before I pass it to a Log4J log.debug
method:
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 int
or 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 RENAME_SUCCEEDED
variable.
Java ‘sprintf’: assigning a formatted String to another String
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);
Using String.format with multiple variables
Finally, here is an example of how to use multiple variables with the String format
method:
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.out.format
and 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.
this post is sponsored by my books: | |||
#1 New Release |
FP Best Seller |
Learn Scala 3 |
Learn FP Fast |
More “printf” style formatting examples
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.