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 a relative index that enables you to reuse the
argument matched by the preceding format specifier. Simply specify < for the argument
index. For example, the following call to format( ) 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 argument cal need only be passed once, rather than
three times.
The Java printf( ) Connection
Although there is nothing technically wrong with using Formatter directly (as the preceding
examples have done) when creating output that will be displayed on the console, there is
a more convenient alternative: the printf( ) method. The printf( ) method automatically uses
Formatter to create a formatted string. It then displays that string on System.out, which
is the console by default. The printf( ) method is defined by both PrintStream and
PrintWriter. The printf( ) method is described in Chapter 19.
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home