Java - Printf-style Formatting Input


Formatting data using a Formatter requires two types of inputs:

  • A format string
  • A list of values

Format String

The format string is the template which contains zero or more occurrences of fixed texts and zero or more embedded format specifiers.

No formatting is applied to the fixed text.

A format specifier acts as a placeholder for the formatted data inside the format string and it specifies how the data should be formatted.

Suppose you want to print a text with the birth date of a person.

You can convert the above text into a template as shown:

<month> <day>, <year> is <name>'s birth day.

You need four input values (month, day, year, and name) to use the above template to get a formatted text.

A placeholder is called a format specifier. A template is called a format string.

Format specifier

A format specifier always starts with a percent sign %.

You can convert the template into a format string, which can be used with the Formatter class as follows:

%1$tB %1$td, %1$tY is %2$s's birth day.

"%1$tB", "%1$td", "%1$tY", and %2$s" are four format specifiers, whereas " " , ", ", "is ", and "'s birth day." are fixed texts.

The following code uses the above format string to print formatted text.


import java.time.LocalDate;
import java.time.Month;

public class Main {
  public static void main(String[] args) {
    LocalDate dob = LocalDate.of(2017, Month.JANUARY, 16);
    System.out.printf("%1$tB %1$td, %1$tY is %2$s's birth day.", dob, "John");

  }//from   w w  w. java2 s  . co  m