Minimum Field Width Specifier
An integer placed between the % sign and the format conversion code acts as a minimum field-width specifier. This pads the output with spaces to ensure that it reaches a certain minimum length. If the string or number is longer than that minimum, it will still be printed in full. For example:
The first and third line displays the number 12345 in its default width. The second line displays that value in a 8-character field. The default padding is done with spaces. If you want to pad with 0’s, place a 0 before the field-width specifier. For example, %05d will pad a number of less than five digits with 0’s so that its total length is five. For example:
The field-width specifier can be used with all format specifiers except %n. The minimum field-width modifier is often used to produce tables in which the columns line up. For example, the following program produces a table of squares and cubes for the numbers between 1 and 10.
Program
Program Source
public class Javaapp { public static void main(String[] args) { Formatter fmt = new Formatter(); fmt.format("%04d | %04d | %04d", 0, 0, 0); for (int i = 1; i < 10; i++) { fmt.format("%n%04d | %04d | %04d", i, i*i, i*i*i); } System.out.println(fmt); fmt.close(); } }