7 Examples of formatting String Java - String.format() and printf() Examples

You can format String in Java either by using the String.format() method or by using the System.printf() method, both use TextFormat class to format String input internally. Both of these methods are inspired from C-Style printf() method and formatting instructions are very similar to C e.g. %s for String, %d for numeric, %f for floating-point value, and %n for new lines, etc, but it is not exactly same as C. Some customization has been made to accommodate some Java language features. 

Java's String formatting is also more strict than C's, for example, if a conversion is incompatible with a flag then Java throws an Exception ( java.util.IllegalFormatConversionException), while in C, incompatible flags are silently ignored.

As a programmer, what is most important to learn regarding String formatting is those flags, as long as you know about them or have an idea where to refer, you are good. If your job involves lots of String formatting stuff then you will automatically know the nitty-gritty of it like some advanced uses of the String.format() method, which we will see in this article.

Many developers also confuse between printf() and format(), they are exactly same, only different is one is declared in java.lang.String class and other is on java.io.PrintStream.  

You should use String.format() method if you need a formatted String and use System.out.printf() if you need to display formatted String on the console.

7 Examples of formatting String and Text in Java

Here are a couple of examples of formatting String or text in Java. There are two key things to learn, first, you can use either printf() or format() to format a String. The key difference between them is that printf() prints the formatted String into console much like System.out.println() but the format() method returns a formatted string, which you can store or use the way you want.

The second most important thing you need to learn for formatting String in Java is formatting instructions like %s, %d, %n etc. The whole formatting process works based on the instruction you give.
// formatting String with dynamic String and Integer input
System.out.printf("length of String %s is %d %n", "abcd", "abcd".length());

This will print "length of String abcd is 4 ", you can see that "abcd" and "4" are dynamically appended into given String based upon formatting instruction and values you passed.
// re-ordering output using explicit argument indices
System.out.printf("%3$2s, %2$2s, %1$2s %n", "Tokyo", "London", "NewYork" );

This will print "NewYork, London, Tokyo", you can see that even though you passed Tokyo as first parameter it appeared last in formatted String because we have  re-ordered output using explicitly argument indices.

// formatting Date to String using %D flag, %D is for MM/dd/yy format
System.out.printf("Date in MM/dd/yy format is %tD %n", new Date());

This example will print "Date in MM/dd/yy format is 12/07/16", you can see that today's date is nicely formatted in MM/dd/yy format. This is probably the easiest way to format a date as a String in Java, It doesn't require you to create a SimpleDateFormat object and handle the formatting of the date by yourself.

// formatting floating-point number as String, you can pass both float and double
System.out.printf("Value of PIE is %f %n", Math.PI);

This will print "Value of PIE is 3.141593 ", you can see that value of PI is printed up to 5 decimal places which are default precision applied by format() method of String class. Though, you can control up to how many decimal places you want to use as shown in the next example.

You should also note that Math.PI is a double constant, which means you can pass both float and double variables by using %f formatting instruction. You can see more examples of formatting float and double in my article  5 examples of formatting double and float in Java.

/ if you want to output to be only up to a certain decimal place then you can specify
// in your formatting instruction, the following will format String up to 2 decimals
System.out.printf("Value of PIE up to 2 decimal place is %.2f %n", Math.PI);

This code will print "Value of PIE up to 2 decimal place is 3.14 ", you can see that value of PI is not only printed up to two decimal places as instructed.  Btw, you have more option when it comes to formatting numbers in Java e.g. you can use NumberFormat and DecimalFormat for more flexibility and more formatting styles.

// following will format decimals up to 3 decimals
System.out.printf("Value of PIE up-to 3 decimals is %.3f", Math.PI);

This example will print "Value of PIE up to 3 decimals is 3.142", you can now see that value of PI is printed up to 3 decimal places because of formatting instruction "%.3f". You can change it to whatever value you want depending upon your requirement.

// adding leading zeros into numbers
int number = 7;      
String str = String.format("%03d", 7);  // 0007    
System.out.printf("original number %d, numeric string with padding : %s", 7, str);
You can even use the printf() and format() method to add leading zeros to a number. For example, if you want to convert 7 to 007, you can just do that using the format() method as shown above. This is particularly useful when you always have to send 4 digits or 5 digit codes and need to add leading zeros accordingly.  See this tutorial to learn more about adding leading zeros to a number in Java.

7 Examples of String.format() and printf() in Java - Formatting Text and String in Java

Things to remember about formatting String in Java

Now, let's revise and learn few more important things about formatting text or String in Java.

1. Both String.format() and PrintStream.printf() are overloaded to support locale-specific formatting.

2. The String.format() method throws java.util.IllegalFormatConversionException if you pass in-compatible type e.g. passing Integer for flag %s, which expects a String object.

3. Some of the most common flags are %s for String, %d for decimal integer and %n is used to insert a new line in formatted String. %n actually return the platform-specific line separator as returned by System.getProperty("line.separator"), So its platform-independent.

4. The position of argument is in the order they appear in source String e.g. if source String is "%s has length %d" then the first argument would be of String type and the second argument would be of decimal integer type.

5. The String.format() method is strict about type, so if formatting flag is %s then you must pass a String object, otherwise it will throw java.util.IllegalFormatConversionException.

6. You can also format Date as String using String.format() method, surprised? Yes, even I got surprised when I discovered that there is a way to format Date in Java without using SimpleDateFormat. You can use the %tD flag to format Date as "MM/dd/yy" String.

If you are new to Java and want to learn more about its core features including text, number and currency formatting, then I would suggest you joining any free Java online courses from the list I have shared earlier. This will help you to learn essential concepts in Java in quick time in more structured ways.

Errors and Exception while formatting String in Java

If you give an invalid conversion or formatting flag, here we had passed %D to format Date but the correct flag is %tD, hence this error.

Exception in thread "main" java.util.UnknownFormatConversionException: Conversion = 'D'
at java.util.Formatter$FormatSpecifier.conversion(Formatter.java:2646)
at java.util.Formatter$FormatSpecifier.(Formatter.java:2675)
at java.util.Formatter.parse(Formatter.java:2528)
at java.util.Formatter.format(Formatter.java:2469)
at java.util.Formatter.format(Formatter.java:2423)
at java.lang.String.format(String.java:2790)
To solve this error just correct the formatting instruction or the value you are passing, both must be in sync to avoid this error.

That's all about how to format String in Java. You can use String.format() or PrintStream.printf() to format String, which internally uses Formatter class. It allows you to format dates, floating-point numbers, numeric, etc. Please see Javadoc of Formatter class for all sorts of formatting instructions. 

We have barely touched the surface of different formatting flags but this is what you need at 90% of the time. Some of the most common uses for formatted String is on toString() method, or formatting float and doubles in Java.

Over to you now, what is your favorite way to format String in Java?

No comments:

Post a Comment

Feel free to comment, ask questions if you have any doubt.