Tutorial

Java printf() - Print Formatted String to Console

Published on August 3, 2022
Default avatar

By Anupam Chugh

Java printf() - Print Formatted String to Console

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

We’ve already discussed Java println() method in a previous tutorial. Today, we’ll discuss the printf() method and its various implementations in detail. Ready. Get. Set. Go!

Java printf()

  • printf() method is not only there in C, but also in Java.
  • This method belongs to the PrintStream class.
  • It’s used to print formatted strings using various format specifiers.

Syntax

Following are the syntaxes available for the printf() method:

System.out.printf(string);
System.out.printf(format, arguments);
System.out.printf(locale, format, arguments);

The first one does not do any formatting though and it’s like the println() method.

System.out.format() is same as System.out.printf() method.

Difference between String.format() and System.out.printf()

  1. String.format() returns a formatted string. System.out.printf() also prints a formatted string to the console.
  2. printf() uses the java.util.Formatter class to parse the format string and generate the output.

Format Specifiers

Let’s look at the available format specifiers available for printf:

  • %c character
  • %d decimal (integer) number (base 10)
  • %e exponential floating-point number
  • %f floating-point number
  • %i integer (base 10)
  • %o octal number (base 8)
  • %s String
  • %u unsigned decimal (integer) number
  • %x number in hexadecimal (base 16)
  • %t formats date/time
  • %% print a percent sign
  • \% print a percent sign

Note: %n or \n are used as line separators in printf().

Escape Characters

Following are the escape characters available in printf():

  • \b backspace
  • \f next line first character starts to the right of current line last character
  • \n newline
  • \r carriage return
  • \t tab
  • \\ backslash

Format Specifiers Full Syntax

Let’s look at the full syntax of format specifiers with the extended set:

%<flags><width><.precision>specifier

flags can be set as + for right-aligning, and - for left-aligning. Next, fire up your Jshell and start using printf()!

Number Formatting

Here’s an example:

|  Welcome to JShell -- Version 12.0.1
|  For an introduction type: /help intro

jshell> int x = 10
x ==> 10

jshell> System.out.printf("Formatted output is: %d %d%n", x, -x)
Formatted output is: 10 -10

Let’s use some precision formatting:

jshell> float y = 2.28f
y ==> 2.28

jshell> System.out.printf("Precision formatting upto 4 decimal places %.4f\n",y)

Precision formatting upto 4 decimal places 2.2800

jshell> float z = 3.147293165f
z ==> 3.147293

jshell> System.out.printf("Precision formatting upto 2 decimal places %.2f\n",z)

Precision formatting upto 2 decimal places 3.15

As you can see it rounds off to the next decimal in the second case.

Width Specifier, Aligning, Fill With Zeros

In this section, we’ll see three examples for each of these:

jshell> System.out.printf("'%5.2f'%n", 2.28);
' 2.28'

As you can see the width specifier allocates 5 characters width. The content is right aligned by default. Filling with zeros Empty spaces to the left of the first character can be filled with zeroes as shown below:

jshell> System.out.printf("'%05.2f'%n", 2.28);
'02.28'

jshell> System.out.printf("'%010.2f'%n", 2.28);
'0000002.28'

jshell> System.out.printf("'%010.2f'%n", -2.28);
'-000002.28'

jshell> System.out.printf("'%010.2f'%n", 1234567.89);
'1234567.89'

jshell> System.out.printf("'%010.2f'%n", -1234567.89);
'-1234567.89'

Aligning By default, it is a + which means right aligned.

jshell> System.out.printf("'%10.2f'%n", 2.28);
'      2.28'

The following code, aligns to the left:

jshell> System.out.printf("'%-10.2f'%n", 2.28);
'2.28      '

Using Comma and Locale:

jshell> System.out.printf(Locale.US, "%,d %n", 5000);
5,000

String, Boolean formatting

Let’s look at String formatting with a few basic examples:

jshell> System.out.printf("%s %s!%n","Hello","World");
Hello World!
jshell> System.out.printf("%s\f%s!%n","Hello","World!");
Hello
     World!!
jshell> System.out.printf("%s\\%s!%n","Hello","World!");
Hello\World!!

Uppercase:

jshell> System.out.printf("%s %S!%n","Hello","World");
Hello WORLD!

Boolean formatting examples are given below:

jshell> System.out.printf("%b%n", false);
false

jshell> System.out.printf("%b%n", 0.5);
true

jshell> System.out.printf("%b%n", "false");
true

Time Formatting

‘H’, ‘M’, ‘S’ - Hours, Minutes, Seconds ‘L’, ‘N’ – to represent the time in milliseconds and nanoseconds accordingly ‘p’ – AM/PM ‘z’ – prints out the difference from GMT.

jshell> Date date = new Date();
date ==> Fri Apr 19 02:15:36 IST 2019

jshell> System.out.printf("%tT%n", date);
02:15:36

jshell> System.out.printf("H : %tH, M: %tM, S: %tS%n",date,date,date)
H : 02, M: 15, S: 36

The latter one requires many arguments which are the same. Instead, we can replace them with a single one:

jshell> System.out.printf("%1$tH:%1$tM:%1$tS %1$Tp GMT %1$tz  %n", date)
02:15:36 AM GMT +0530

Date Formatting

Date formatting has the following special characters A/a - Full day/Abbreviated day B/b - Full month/Abbreviated month d - formats a two-digit day of the month m - formats a two-digit month Y - Full year/Last two digits of the Year j - Day of the year

jshell> System.out.printf("%s %tB %<te, %<tY", "Current date: ", date);
Current date:  April 19, 2019

jshell> System.out.printf("%1$td.%1$tm.%1$ty %n", date);
19.04.19

jshell> System.out.printf("%s %tb %<te, %<ty", "Current date: ", date);
Current date:  Apr 19, 19

Conclusion

In this tutorial, we discussed the various types of formatting possible using printf() method.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about us


About the authors
Default avatar
Anupam Chugh

author

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
January 4, 2022

one of the best refs… great …Thanks…

- ALIREZA MAJIDI

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    December 8, 2020

    This was a really good explanation, thank you!

    - Hugo

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      November 10, 2019

      Thanks for such a detailed explanation

      - Ashutosh Aneja

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        May 15, 2019

        thanks so and it perfect

        - sadiqullah

          Try DigitalOcean for free

          Click below to sign up and get $200 of credit to try our products over 60 days!

          Sign up

          Join the Tech Talk
          Success! Thank you! Please check your email for further details.

          Please complete your information!

          Get our biweekly newsletter

          Sign up for Infrastructure as a Newsletter.

          Hollie's Hub for Good

          Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

          Become a contributor

          Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

          Welcome to the developer cloud

          DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

          Learn more
          DigitalOcean Cloud Control Panel