Java - Printf-style Formatting Syntax

Syntax

The general syntax for a format specifier is as follows:

%<argument-index$><flags><width><.precision><conversion>

Other than the % and <conversion> parts, all other parts are optional.

There is no space between any two parts of a format specifier.

% marks the start of a format specifier.

To use % as the part of a fixed text, use two consecutive % as %%.

Argument Index

<argument-index$> marks the index of the argument that the format specifier refers to.

It consists of an integer in base-10 format followed by a $.

The first argument is referred to as 1$, the second as 2$, and so on.

You can refer to the same argument multiple times inside the same format string.

Flag

<flags> controls the output format.

It is a set of characters. The valid values for <flags> depend on the data type of the argument that the format specifier refers to.

Width

<width> sets the minimum number of characters that need to be written to the output.

<.precision> sets the maximum number of characters to be written to the output.

Its exact meaning varies depending on the value for <conversion>.

It is a decimal number starting with a dot .

Conversion

<conversion> marks how the output should be formatted.

Its value depends on the data type of the argument, which the format specifier refers to.

There are two special format specifiers:

  • "%%" format specifier outputs "%"
  • "%n" outputs a platform-specific newline character.

The following snippet of code demonstrates the use of these two special format specifiers:

System.out.printf("Interest rate is 10%%.%nJohn%nDonna");