Formatter and printf


Sometimes you want more control over printing than System.out.print and System.out.println give you. For example, you might wish to print numbers in neat columns. The Formatter class gives you this extra control.

The basic use of a Formatter is as follows:

Formatter f = new Formatter();
f.format(format-string, value, ..., value);

In this code,

  1. Line 1 creates a new formatter.
  2. Line 2 substitutes the values into the format-string according to its format specifiers, and adds that string to the formatter.
  3. Line 3 calls the formatter's toString() method and prints the result.
  4. Line 4 releases the resources associated with the formatter.

If you simply want to print a formatted string, the above can be abbreviated as:

System.out.printf(format-string, value, ..., value);

Here's an example use:

Formatter f = new Formatter();
f.format("The value of %s is %7.4f", "pi", Math.PI);
f.format(" and %s is %7.4f.", "e", Math.E);

The value of pi is 3.1416 and e is 2.7183.

In the above example, a String is substituted for the %s and a double for the %7.4f; the double occupies 7 character positions, 4 of them after the decimal point.

A format specifier has the following syntax (illegal spaces added for clarity):

argument-indexflags width conversion

The optional argument-index lets you choose which value (counting from 1, not 0) to put in this place.

The optional width is the number of character positions to use. For floating point numbers, the syntax totalWidth.fractionWidth specifies the total number of character positions to use, and the number of digits after the decimal point.

Here are the available flags (which are optional) and a few of the possible conversions (one of which must be present):

- left justification
# alternate conversion format
0 pad with zeros instead of spaces
space positive numbers are preceded by a space
+ positive numbers are preceded by a plus sign
, numbers include grouping separators
( negative numbers are enclosed in parentheses
%b boolean
%c character
%d integer
%e scientific notation
%f floating point
%s string
%tc complete date and time


a newline on this platform
%% the character %

There is a great deal more to the Formatter class than this. In particular, there are more than 30 conversions specified for dates and times.