Skip to main content

See also:

How to use formatted printf() in Java

For more information on formatted output in Java, see the Java PrintStream class.
For more information on formatted output in Java, see the Java PrintStream class.
sanchezcl/SXC

The Java PrintStream class includes two methods that perform formatted output: printf() and format(). These methods are equivalent, and they are similar to the printf() function in the C programming language. Here are some examples on how to format output in Java with printf().

Formatting Integers

The following examples show how to format an integer normally, with leading zeroes and with commas.

System.out.printf("%d%n", 12345); //12345

System.out.printf("%08d%n", 12345); //00012345

System.out.printf("%,8d%n", 12345); // 12,345

Formatting Floats

These examples show how to format a float value. Some statements show how to specify the number of decimal places. The last example shows how to left-justify the number.

System.out.printf("%f%n", Math.PI); //3.141593

System.out.printf("%.3f%n", Math.PI); //3.142

System.out.printf("%8.3f%n", Math.PI); // 3.142

System.out.printf("%-8.3f%n", Math.PI); //3.142

Formatting Dates

These examples show how to format dates and times in Java. Only some of the formatting parameters are shown below. There are many more to choose from.

Calendar cal = Calendar.getInstance();

System.out.printf("%tB %te, %tY%n", cal, cal, cal); //September 28, 2013

System.out.printf("%tl:%tM %tp%n", cal, cal, cal); //2:41 pm

System.out.printf("%tD%n", cal); //09/28/13

These are just some of the ways to format output in Java using the printf() method. For more information on formatted output in Java, see the Java PrintStream reference.

For more articles, please subscribe, add or follow me here.