THE Java™ Programming Language, Fourth Edition

(Jeff_L) #1

remember to do this yourself. No width, precision, or flag values can be used with the line separator
conversion.


The following sections look at the format specifiers for numeric, character, and general conversions. The
formatting conversions for dates and times are discussed in "Using Formatter with Dates and Times" on page



  1. The Formatter class also supports formatting for instances of the java.math.BigInteger and
    java.math.BigDecimal classes, but those are not discussed hereconsult the Formatter class
    documentation for information concerning those classes.


22.1.1. Format Specifiers


The general form of a format specifier for general, character, or numeric conversions is


%[argument_index][flags][width][.precision]conversion


where everything except the % and the conversion indicator are optional.


If there is an error in the format string, a mismatch between the conversion and the other formatting requests,
or a mismatch between the conversion and the argument type supplied, then an
IllegalFormatException of some form will be thrown. These exceptions are described later.


The argument index is an optional indicator of which argument this format specifier should be applied to. This
is very useful for referring to the same argument multiple times within the same format string. The argument
index can take two forms: a number indicating which argument it applies to, followed by a $ character; or the
< character meaning "the same argument as the previous format specifier." If the argument index is not
present, then each unmarked format specifier is numbered sequentially, and it is that argument to which the
format specifier is applied. This numbering ignores the presence of any indexed format specifiers. For
example, given


System.out.printf("%3$d %d %2$d %<d %d %n", 1, 2, 3);


the output is


3 1 2 2 2


The first specifier explicitly applies to argument three; the second is the first non-indexed specifier so it
applies to argument one; the third specifier explicitly applies to argument two; the fourth specifier applies to
whatever the third did, so that is again two; the fifth specifier is the second non-indexed specifier so it also
applies to argument two.


If any format specifier indicates an argument that does not exist, then you get a
MissingFormatArgumentException. Examples of this kind of error are using %3$ when there are
only two arguments, or using %< as the first format specifier.


The meaning of flags, width, and precision is similar for the different conversions but the details differ
depending on the exact kind of conversion, as discussed in the following sections.

Free download pdf