Skip to main content
  1. Tech
  2. Gadgets & Tech
  3. Internet

How to use formatted printf() in Java

See also

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.

Advertisement

Don't Miss

  • Fable
    'Fable Legends' hands-on: A new breed of 'Fable' is here, you should be excited, we are
    Games Preview
  • Microsoft
    Microsoft shuts down entertainment studios on the heels of massive layoffs news
    Video
    Tech Buzz
  • Destiny
    The 'Destiny' beta: 7 things we absolutely love about Bungie's new franchise
    Games Feature
  • GoTenna
    GoTenna allows you to send text messages when you have no service
    Headlines
  • Far Cry
    'Far Cry 4' exclusive: Animals, avalanches, oxygen, side content and much more
    Games Interview
  • Facebook
    Facebook releases a mobile app designed for famous people to interact with their fans
    Video
    Headlines