Formatting With printf() in Java
Java printf() is a method that belongs to the PrintStream class and it is very similar to the printf() function in C. It is used to format the output and print it to the console. This method uses the java.util.Formatter class to parse and format the output. In this tutorial, we will learn how to use the printf() method.
Java Printf() Method
As discussed above, the printf() method is used to format strings in Java. The general syntax of this method is shown below.
System.out.printf(string)
System.out.printf(format string, comma separated variables values or objects)
System.out.printf(locale, format string, comma-separated variables values or objects)
- If the locale is passed, then the formatting takes place according to the region mentioned.
- We usually use just two parameters - one is the formatting string and the other one includes objects, variables, or values.
- The formatting string is what defines how the output will be visible to the user. The general structure of the formatting string is shown below. The conversion characters must be included if we wish to output some values, but the other modifiers are optional.
%[flags][width][.precision][conversion-characters]
- Without any specifiers and variables, printf() works exactly like print() or println(). The below example demonstrates how the output of printf() and println() is the same if the formatting string is not used.
public static void main(String args[])
{
System.out.println("Printing using println().");
System.out.printf("Printing using printf().");
}
Printing using println().
Printing using printf().
Characters Formatting using print() in Java
The formatting string must include conversion characters according to the data type of the variables or values that we are trying to print. The following list includes some of the most commonly used conversion characters.
- c formats a character or char.
- s formats a string.
- d formats integers.
- f formats floating-point or decimals.
- t formats date and time.
- b formats boolean values or conditional expressions.
- e formats exponential floating-point numbers.
- %n is used as a newline character and takes the cursor to the next line.
public static void main(String args[])
{
System.out.printf("Printing an integer %d %n", 10);
System.out.printf("Printing a floating-point number %f %n", 10.0);
System.out.printf("Printing an exponential floating-point number %e %n", 10.0);
System.out.printf("Printing a string %s %n", "String");
System.out.printf("Printing a character %c %n", 'A');
}
Printing an integer 10
Printing a floating-point number 10.000000
Printing an exponential floating-point number 1.000000e+01
Printing a string String
Printing a character A
We must use the correct conversion character according to the data type of the variable or value. If they do not match then we will get an IllegalFormatConversionException. Consider the example shown below where the conversion character for integers is used to format a string.
public static void main(String args[])
{
System.out.printf("%d", "ABC");
}
Exception in thread "main" java.util.IllegalFormatConversionException: d != java.lang.String
at java.base/java.util.Formatter$FormatSpecifier.failConversion(Formatter.java:4426)
at java.base/java.util.Formatter$FormatSpecifier.printInteger(Formatter.java:2938)
at java.base/java.util.Formatter$FormatSpecifier.print(Formatter.java:2892)
at java.base/java.util.Formatter.format(Formatter.java:2673)
at java.base/java.io.PrintStream.format(PrintStream.java:1209)
at java.base/java.io.PrintStream.printf(PrintStream.java:1105)
at abc.fileDemo.main(fileDemo.java:6)
Some conversion characters can also be used to convert letters to uppercase. For example, if we use "C" instead of "c", then the character value will be printed in uppercase. The same rule can be applied for strings and boolean. Remember that this will not work the other way round i.e. "c" will not convert uppercase to lowercase.
Example: Formatting Lowercase and Uppercase in print()
The following code example demonstrates the use of uppercase and lowercase conversion characters.
public static void main(String args[])
{
System.out.printf("%c%n", 'a');
System.out.printf("%C%n", 'a');
System.out.printf("%s%n", "lowercase");
System.out.printf("%S%n", "uppercase");
System.out.printf("%b%n", 10 < 5);
System.out.printf("%B%n", 10 < 5);
}
a
A
lowercase
UPPERCASE
false
FALSE
Flags in printf() Method
Flags are used to modify the formatted output in different ways. For example, hyphen(-) can be used to left-justify our string and comma(,) can be used to add thousands-separator.
public static void main(String args[])
{
System.out.printf("%d%n", 1000000);//without flag
System.out.printf("%,d", 1000000);//with flag
}
1000000
1,000,000
Setting Width with printf() Method
The width is used to specify the minimum number of spaces in the console for the output. For example, if we use "%5s" then at least 5 places will be allocated. If the value to be printed has a smaller length then padding would be added in front of it, else the value will be printed as it is. Consider the following example to better understand it.
public static void main(String args[])
{
System.out.printf("%5s", "string");
}
The output for the above code will simply be the word "string".
However, the output with padding will look like " '---------string' ", where a hyphen denotes an empty space.
public static void main(String args[])
{
System.out.printf("'%15s'", "string");
}
Setting Precision with printf() Method
The precision can be used to specify the digits after the decimal point for floating-point numbers. It can also be used to extract substrings.
public static void main(String args[])
{
System.out.printf("%.4f %n", 3.14159265359);//rounding pi up to 4 decimal places
System.out.printf("%.3s", "string");//first three characters of the string
}
3.1416
str
Formatting Numbers using printf()
As discussed above, %d is used to format integers and %f is used to format floating-point numbers. By default, %f will add extra zeroes to the output. We can limit them by using precision modifiers.
public static void main(String args[])
{
System.out.printf("Integer: %d%n", 10);
System.out.printf("Float: %f", 10.01);
}
Integer: 10
Float: 10.010000
We can also format the numbers with thousands-separator using the comma flag. We can also specify the region by using locale. For example, in Italy dots are used but the English use the comma.
public static void main(String args[])
{
System.out.printf(Locale.ENGLISH, "%,d%n", 1000000);
System.out.printf(Locale.ITALY, "%,d", 1000000);
}
1,000,000
1.000.000
We can also pad the number with zeroes by entering a 0 before the conversion character and specifying the width.
public static void main(String args[])
{
System.out.printf("%010d%n",158);
}
0000000158
Formatting Date and Time using printf()
For date and time formatting, we have to use certain suffixes along with the "t" conversion character. Let's take a look at date and time formatting separately.
Time Formatting
We can simply print the time portion from a date by using the "T" suffix with the "t" conversion character.
public static void main(String args[])
{
Date date = new Date();
System.out.printf("Time: %tT", date);
}
Time: 18:07:38
The following suffixes are used for time formatting.
- H is used for extracting the hours part of the date.
- M is used for extracting the minutes part of the date.
- S is used for extracting the seconds part of the date.
- L is used for extracting the milliseconds part of the date.
- N is used for extracting the nanoseconds part of the date.
- p is used to print a.m. or p.m.
- z is used to print the time zone.
Take a look at the following code to understand time formatting better.
public static void main(String args[])
{
Date date = new Date();
System.out.printf("Hours: %tH Minutes: %tM Seconds: %tS Milliseconds: %tL%n", date, date, date, date);
}
Hours: 17 Minutes: 58 Seconds: 26 Milliseconds: 793
As we can see in the code above, we need to mention the date variable several times. There is a simple way to get around this by using the index reference 1$ in the format string.
public static void main(String args[])
{
Date date = new Date();
System.out.printf("Hours: %1$tH Minutes: %1$tM Seconds: %1$tS Milliseconds: %1$tL%n",
date);
}
Hours: 18 Minutes: 01 Seconds: 32 Milliseconds: 783
Date Formatting
The following is a list of the most commonly used suffixes for date formatting.
- A is used to print the full name of the day.
- a is used to print the abbreviated name of the day
- B is used to print the full name of the month.
- b is used to print the abbreviated name of the month.
- d is used to print the two-digit day of the current month.
- m is used to print the two-digit month of the year.
- Y is used to output the year in four digits.
- y is used to output the year in two digits.
Consider the example below to better understand date formatting.
public static void main(String args[])
{
Date date = new Date();
System.out.printf("Day: %tA Date: %td Month: %tB Year: %tY%n",
date, date, date, date);
}
Day: Thursday Date: 08 Month: July Year: 2021
We can use the 1$ index reference for date formatting as well.
public static void main(String args[])
{
Date date = new Date();
System.out.printf("Day: %1$tA Date: %1$td Month: %1$tB Year: %1$tY%n",
date);
}
Day: Thursday Date: 08 Month: July Year: 2021
Summary
One must know how to properly format and print the output so that it is easy to read and understand. Java has a printf() method that is used for formatting outputs. It uses a format string that is composed of conversion characters and optional modifiers. In this tutorial, we learned how to format integers, strings, boolean, dates, and time using the printf() method.