What is printf method in Java?

The Java printf method is used to write the formatted strings. The ‘f’ in printf keyword means formatted. The printf method belongs to the PrintStream and PrintWriter classes.

The syntax of using the printf method

For both classes (PrintStream and PrintWriter), the syntax of using the printf method is the same with two variations:

The first way of using printf:

printf(String format, Object… args)

Where:

  • The format parameter specifies the format string that may contain fixed text and format specifiers. The format specifiers are explained in the coming section.
  • The args are the arguments in the format string referred by the format specifiers.
  • If args are more than format specifiers then no error is thrown. The extra arguments are just ignored.

Second way:

printf(Locale loc, String format, Object… args)

  • There you may specify a locale. If loc is null then no locale is applied. A locale specifies the cultural, geographical or political region.

In the following section, I will show you examples of using the printf Java method to create formatted strings.

An example of printf with different specifiers

Before you see the list of specifiers in the following section, have a look at an example of using the printf with a few specifiers. In the example, the decimal integer, float number, a character, and a string is used with printf for writing a formatted string as follows:

public class string_b {

          public static void main(String args[]) {

                  int x = 20;

                  float y = 5.5f;

                  char c = 'J';

                  String str = "Hello Java";

                 

                  //Displaying formatted string

                  System.out.printf("The formatted string: %d %f %c %s", x , y, c, str);
        }

}

The output:

The formatted string: 20 5.500000 J Hello Java

List of format specifiers that can be used in printf

The format specifiers include the following:

  • conversion characters
  • precision
  • flags
  • width

% conversion-character [flags] [width] [.precision]

Following is the list of conversion characters that you may use in the printf:

Conversion Character Purpose
%d for signed decimal integer
%f for the floating point
%o octal number
%c for a character
%s a string
%i use for integer base 10
%u for unsigned decimal number
%x hexadecimal number
%% for writing % (percentage)

The flags list include:

  • justify left
  • + if you require to output the + or minus in the formatted string.
  • ^ uppercase
  • 0 for zero-padded numeric values

The width option specifies the maximum number of characters to be written in the output.

You may use the precision for the number of digits after the decimal point for floating numbers.

An example of specifying precision in printf

In the first example, you might notice the display of float value. For the variable y=5.5, the printf displayed: 5.500000.

You may use the precision that specifies the number of digits after the decimal point for floating numbers.  See an example below where two double type variables are declared and assigned the values as follows:

a = 35.55845

b = 40.1245414

By using printf, I will display two digits after the decimal point for variable a and four digits for b:

public class string_b {

          public static void main(String args[]) {

                  double a = 35.55845, b = 40.1245414;

                  //printf precision

                  System.out.printf("x = %.2f %n b = %.4f", a, b);
        }

}

The output:

x = 35.56

b = 40.1245

The example of formatting strings

The following example shows formatting the string with ‘%s’ specifier.

public class string_b {

          public static void main(String args[]) {

                 String str = "Hello Printf";

                 char x = 'z';

                 System.out.printf("%s", str);

                

                 //Displaying with upper case

                 System.out.printf("%n%S", str,x);

          }

}

The output:

Hello Printf

HELLO PRINTF

The ‘%S’ displays the string in upper case.

Example of displaying date with locale

The following example displays the current date set in the local system. The second statement displays the current day:

import java.util.Date;

public class string_b {

          public static void main(String args[]) {

           Date dpf = new Date();

           System.out.printf("Current date/time: %tc", dpf);

                 System.out.printf("%n Name of the Day, Today: %tA/%TA\n", dpf, dpf);

          }

}

The output:

Current date/time: Mon Nov 20 16:45:19 2017

Name of the Day, Today: Monday/MONDAY

Displaying date in day, Month name and year example

See the following example for displaying the local date in the following format:

20 November, 2014

import java.util.Date;

public class string_b {

          public static void main(String args[]) {

           Date dpf = new Date();

           System.out.printf("Local date: %1$td %1$tB, %1$tY", dpf);

          }

}

The Output:

Local date: 11 December, 2014

Formatting time example

The following example shows formatting the local time by using date object with Java printf():

import java.util.Date;

public class string_b {

          public static void main(String args[]) {

                 Date timepf = new Date();

                

                 System.out.printf( "The current local time: %1$tI:%1$tM:%1$tS %1$tZ", timepf );

          }

}

The output:

The current local time: 06:06:33 PKT

Using argument index example

The ‘$’ can be used to refer the number of argument in the printf Java method. This is useful for situation where you have multiple variables of the same type.

For example, in one of the above example, we used single float. If we have two or more float variable, then how to identify both? This is where argument index ‘$’ plays its role.

You may use the ‘$’ as follows:

  • ‘%5$ – means fifth argument
  • ‘%2$ means the second argument
  • ‘%10$ means tenth argument and so on.

See a demo below where I declared char, int and float variables – two for each type. All are used in the string formatting and see how all are differentiated:

public class string_b {

          public static void main(String args[]) {

                 char a = 'x' , b = 'y';

                 int  int_a = 20, int_b = 30;

                 float flt_c = 5.5f, flt_d = 7.7f;



                 System.out.printf( "Second arg:  %2$c", a,b, int_a, flt_c, flt_d);

                 System.out.printf( "%nFourth arg:  %4$d", a,b, int_a, int_b, flt_c, flt_d);

                 System.out.printf( "%nFifth arg:  %5$.2f", a,b, int_a, int_b, flt_c, flt_d);

                



          }

}

The output:

Java printf

Displaying ‘%’ in formatted string

Since the percentage sign (%) is used for formatting strings in Java then how we may display % in the formatted strings? The following example shows that:

public class string_b {

          public static void main(String args[]) {

                 float marks = 98.50f;

                 System.out.printf( "I got %.2f%% marks. Hurray!", marks );

          }

}

The output:

I got 98.50% marks. Hurray!

So, using the percentage twice is the way out for including a % sign in the Java formatted string using printf.

Displaying the hashcode example

For displaying the hashcode, use the %h specifier. See the example code below:

public class string_b {

          public static void main(String args[]) {

                

                    System.out.printf( "'Java' hashcode is %h\n", "Java" );

                    System.out.printf( "'java' hashcode is %h\n", "java" );

          }

}

The output:

‘Java’ hashcode is 231e42

‘java’ hashcode is 31aa22

The code for displaying commas with big numbers

In different scenarios, you may require displaying commas with numbers e.g. showing the amount as:

47,145,25.55

The following example shows how you may do this with int, float and double numbers formatting:

public class string_b {

          public static void main(String args[]) {

                 int amt_a = 478547;

                 long amt_b = 14578478;

                 double amt_c = 14575457457.121f;

                    System.out.printf( "Int: %,d\n", amt_a );

                    System.out.printf( "long: %,d\n", amt_b );

                    System.out.printf( "double: %,.2f", amt_c );

          }

}

The output:

Int: 478,547

long: 14,578,478

double: 14,575,457,280.00

Difference between PrintStream.printf() and PrintWriter.printf()

As mentioned in the introductory part, both PrintStream and PrintWriter have the printf method. Even the syntax of using printf method is the same for both classes.

The difference is the return value. In the case of PrintStream class, the printf() returns this output stream. Whereas, for the PrintWriter.print(), it returns this writer.

Author - Atiq Zia

Atiq is the writer at jquery-az.com, an online tutorial website started in 2014. With a passion for coding and solutions, I navigate through various languages and frameworks. Follow along as we solve the mysteries of coding together!