Printing an integer using a “field width"
We have seen that we can print an integer value by specifying the value (either by a variable or an expression) in a printf statement. When we do so, Java prints the value using as many “print columns" as needed. For instance, if the value is 782, it is printed using 3 print columns since 782 has 3 digits. If the value is -2345, it is printed using 5 print columns (one for the minus sign).
While this is usually sufficient for most purposes, there are times when it is useful to be able to tell Java how many print columns to use. For example, if we want to print the value of n in 5 print columns, we can do this by specifying a field width of 5, as in:
Instead of the specification %d, we now use %5d. The field width is placed between % and d. The value of n is printed “in a field width of 5".
Suppose n is 279; there are 3 digits to print so 3 print columns are needed. Since the field width is 5, the number 279 is printed with 2 spaces before it, thus: ◊◊279 (◊ denotes a space). We also say “printed with 2 leading blanks/spaces" and “printed padded on the left with 2 blanks/spaces".
A more technical way of saying this is “n is printed right-justified in a field width of 5". “Right-justify" means that the number is placed as far right as possible in the field and spaces added in front of it to make up the field width. If the number is placed as far left as possible and spaces are added after it to make up the field width, the number is left-justified. For example, 279◊◊ is left-justified in a field width of 5.
The minus sign can be used to specify left-justification; %-wd will print a value left-justified in a field width of w. For example, to print an integer value left-justified in field width of 5, we use %-5d.
For another example, suppose n is -7 and the field width is 5. Printing n requires two print columns (one for - and one for 7); since the field width is 5, it is printed with 3 leading spaces, thus: ◊◊◊-7.
You may ask: What will happen if the field width is too small? Suppose the value to be printed is 23456 and the field width is 3. Printing this value requires 5 columns which is greater than the field width 3. In this case, Java ignores the field width and simply prints the value using as many columns as needed (5, in this example).
In general, suppose the integer value v is printed with the format specification %wd where w is an integer, and suppose n columns are needed to print v. There are 2 cases to consider:
• If n is less than w (the field width is bigger), the value is padded on the left with (w ‑ n) spaces. For example, if w is 7 and v is -345 so that n is 4, the number is padded on the left with (7-4) = 3 spaces and printed as ◊◊◊-345.
• If n is greater than or equal to w (field width is the same or smaller), the value is printed using n print columns. In this case, the field width is ignored.