Java - Format Specifier Width and Precision

Introduction

The general syntax for a format specifier for general formatting is

%<argument_index$><flags><width><.precision><conversion>

width sets the minimum number of characters that would be written.

In case of shorter string, the result will be padded with spaces.

The space padding is added to the left of the argument value. If '-' flag is used, space padding is performed to the right.

The values of width and precision together decide the final content of the result.

The precision is applied to the argument before the width is applied.

If the precision is less than the length of the argument, the argument is truncated to the precision, and padded space to match the length of the output.

Consider the following snippet of code:

System.out.printf("'%4.1s'", "Java");

Output:

'   J'

The argument is "Java" and the format specifier is "%4.1s", where 4 is the width and 1 is the precision.

First, the precision is applied that will truncate the value "Java" to "J".

Then, the width is applied, which states that a minimum of four characters should be written to the output.

After the precision is applied, you have only one character left.

Therefore, "J" will be left padded with three spaces to match the width value of four.

Quiz