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 format method of the Java String class to format my text, and I have to say, the resulting Java code is much cleaner this way.
If you're familiar with the sprintf function of other programming languages, I've come to think of the String format method as being the "Java sprintf" method. Let's take a look at a few quick examples.
Here's a quick example of how to use the Java 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 printf or sprintf 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 (which is a very cool thing).
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.
In a way the String.format is like having a Java sprintf method available to you.
For instance, if it helps to see the Java String format method used without the additional log.debug method, here's an example where I use the String.format command 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 Java 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 blog post 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 example page, with printf examples shown in several different programming languages.
Very Useful Info
Very Useful Info Thanks for the same
Post new comment