Java Reference
In-Depth Information
Indices of format specifiers
Indices of Arguments
1
2
3
1
2
3
%s
,
%s
, and
%s
"Ken"
"Lola"
"Matt"
Figure 13-1. Indexes of format specifiers in a format string and indexes of the arguments
Figure 13-1 shows how indices are mapped in the above example. The first "%s" format specified refers to the first
argument, "Ken" . The second "%s" format specified refers to the second argument, "Lola" . And, the third "%s" format
specified refers to the third argument, "Matt" .
If the number of arguments is more than the number of format specifiers in the format string, the extra arguments
are ignored. Consider the following snippet of code and its output. It has three format specifiers (three "%s" ) and four
arguments. The fourth argument, "Lo" , is an extra argument, which is ignored.
System.out.printf("%s, %s, and %s", "Ken", "Lola", "Matt", "Lo");
Ken, Lola, and Matt
A java.util.MissingFormatArgumentException is thrown if a format specifier references a non-existent
argument. The following snippet of code will throw the exception because the number of arguments is one less than
the number of format specifiers. There are three format specifiers, but only two arguments.
// Compiles fine, but throws a runtime exception
System.out.printf("%s, %s, and %s", "Ken", "Lola");
Note that the last argument to the format() method of the Formatter class is a varargs argument. You can also
pass an array to a varargs argument. The following snippet of code is valid even though it uses three format specifiers
and only one argument of array type. The array type argument contains three values for the three format specifiers.
String[] names = {"Ken", "Matt", "Lola"};
System.out.printf("%s, %s, and %s", names);
Ken, Matt, and Lola
The following snippet of code is also valid because it passes four values in the array type argument but has only
three format specifiers:
String[] names = {"Ken", "Matt", "Lola", "Lo"};
System.out.printf("%s, %s, and %s", names);
Ken, Matt, and Lola
Search WWH ::




Custom Search