In this example, the first format specifier matches 30, the second matches 10, and the
third matches 20. Thus, the arguments are used in an order other than strictly left to right.
One advantage of argument indexes is that they enable you to reuse an argument without
having to specify it twice. For example, consider this line:
fmt.format("%d in hex is %1$x", 255);
It produces the following string:
255 in hex is ff
As you can see, the argument 255 is used by both format specifiers.
There is a convenient shorthand called arelative indexthat enables you to reuse the
argument matched by the preceding format specifier. Simply specify<for the argument
index. For example, the following call toformat( )produces the same results as the previous
example:
fmt.format("%d in hex is %<x", 255);
Relative indexes are especially useful when creating custom time and date formats.
Consider the following example:
// Use relative indexes to simplify the
// creation of a custom time and date format.
import java.util.*;
class FormatDemo6 {
public static void main(String args[]) {
Formatter fmt = new Formatter();
Calendar cal = Calendar.getInstance();
fmt.format("Today is day %te of %<tB, %<tY", cal);
System.out.println(fmt);
}
}
Here is sample output:
Today is day 1 of Jan, 2007
Because of relative indexing, the argumentcalneed only be passed once, rather than
three times.
The Java printf( ) Connection
Although there is nothing technically wrong with usingFormatterdirectly (as the preceding
examples have done) when creating output that will be displayed on the console, there is
a more convenient alternative: theprintf( )method. Theprintf( )method automaticallyuses
Formatterto create a formatted string. It then displays that string onSystem.out, which
is the console by default. Theprintf( )method is defined by bothPrintStreamand
PrintWriter. Theprintf( )method is described in Chapter 19.
Chapter 18: java.util Part 2: More Utility Classes 539