Java Reference
In-Depth Information
where everything except the % and the conversion indicator are optional.
If there is an error in the format string, a mismatch between the con-
version and the other formatting requests, or a mismatch between the
conversion and the argument type supplied, then an IllegalFormatExcep-
tion 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 argu-
ment 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 ap-
plied. This numbering ignores the presence of any indexed format spe-
cifiers. 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 spe-
cifier 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.
 
Search WWH ::




Custom Search