Java Reference
In-Depth Information
The following snippet of code is not valid because it uses an array type argument that has only two elements and
there are three format specifiers. A MissingFormatArgumentException will be thrown when the following snippet of
code is run.
String[] names = {"Ken", "Matt"};
System.out.printf("%s, %s, and %s", names); // Throws an exception
Explicit Indexing
When a format specifier specifies an argument index explicitly, it is called explicit indexing. Note that an argument
index is specified just after the % sign in a format specifier. It is an integer in the decimal format and it ends with $ (a
dollar sign). Consider the following snippet of code and its output. It uses three format specifiers: "%1$s" , "%2$s" , and
"%3$s" , which use explicit indexing.
System.out.printf("%1$s, %2$s, and %3$s", "Ken", "Lola", "Matt");
Ken, Lola, and Matt
When a format specifier uses explicit indexing, it can refer to an argument at any index in the argument list using
the index of the argument. Consider the following snippet of code:
System.out.printf("%3$s, %1$s, and %2$s", "Lola", "Matt", "Ken");
Ken, Lola, and Matt
This snippet of code has the same output as the snippet of code before it. However, in this case, the values in
the argument list are not in the same order. The first format specifier, "%3$s" , refers to the third argument, "Ken" ; the
second format specifier, "%1$s" , refers to the first argument, "Lola" ; and the third format specifier, "%2$s" , refers to
the second argument, "Matt" .
It is allowed to reference the same argument multiple times using explicit indexing. It is also allowed not to
reference some arguments inside the format string. In the following snippet of code, the first argument of "Lola" is
not referenced and the third argument of "Ken" is referenced twice:
System.out.printf("%3$s, %2$s, and %3$s", "Lola", "Matt", "Ken");
Ken, Matt, and Ken
Relative Indexing
There is a third way to refer to an argument inside a format specifier, which is called relative indexing. In relative
indexing, a format specifier uses the same argument that was used by the previous format specifier. Relative indexing
does not use an argument-index value. Rather, it uses '<' character as a flag in the format specifier. Since in relative
indexing, a format specifier uses the same argument that is used by the previous format specifier, it cannot be used
with the first format specifier. Remember that to use a relative indexing, there must be a previous format specifier,
which implies that you cannot use the relative indexing for the first format specifier.
 
Search WWH ::




Custom Search