Chapter 18: java.util Part 2: More Utility Classes 533
Specifying a Minimum Field Width
An integer placed between the%sign and the format conversion code acts as aminimum
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. 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,%05dwill pad a number of less than five
digits with 0’s so that its total length is five. The field-width specifier can be used with all
format specifiers except%n.
The following program demonstrates the minimum field-width specifier by applying
it to the%fconversion:
// Demonstrate a field-width specifier.
import java.util.*;
class FormatDemo4 {
public static void main(String args[]) {
Formatter fmt = new Formatter();
fmt.format("|%f|%n|%12f|%n|%012f|",
10.12345, 10.12345, 10.12345);
System.out.println(fmt);
}
}
This program produces the following output:
|10.123450|
| 10.123450|
|00010.123450|
The first line displays the number 10.12345 in its default width. The second line displays
that value in a 12-character field. The third line displays the value in a 12-character field,
padded with leading zeros.
The minimum field-width modifier is often used to produce tables in which the columns
line up. For example, the next program produces a table of squares and cubes for the numbers
between 1 and 10:
// Create a table of squares and cubes.
import java.util.*;
class FieldWidthDemo {
public static void main(String args[]) {
Formatter fmt;
for(int i=1; i <= 10; i++) {
fmt = new Formatter();