Java Reference
In-Depth Information
int a = 5, b = 15, c = 255;
double x = 27.5, y = 33.75;
System.out.printf("x = %f y = %g", x, y);
System.out.printf(" a = %d b = %x c = %o", a, b, c);
TryFormattedOutput.java
Executing this fragment produces the following output:
x = 27.500000 y = 33.750000 a = 5 b = f c = 377
There is no specification of the argument to which each format specifier applies, so the default action is
to match the format specifiers to the arguments in the sequence in which they appear. You can see from the
output that you get six decimal places after the decimal point for floating-point values, and the field width is
set to be sufficient to accommodate the number of characters in each output value. Although there are two
output statements, all the output appears on a single line, so you can deduce that printf() works like the
print() method in that it just transfers output to the command line starting at the current cursor position.
The integer values also have a default output field width that is sufficient for the number of characters in
the output. Here you have output values in normal decimal form, in hexadecimal form, and in octal repres-
entation. Note that there must be at least as many arguments as there are format specifiers. If you remove c
from the argument list in the last printf() call, you get an exception of type MissingFormatArgumentEx-
ception thrown. If you have more arguments than there are format specifiers in the format string, on the
other hand, the excess arguments are simply ignored.
By introducing the argument index into the specification in the previous code fragment, you can demon-
strate how that works:
int a = 5, b = 15, c = 255;
double x = 27.5, y = 33.75;
System.out.printf("x = %2$f y = %1$g", x, y);
System.out.printf(" a = %3$d b = %1$x c = %2$o", a, b, c);
TryFormattedOutput.java
This produces the following output:
x = 33.750000 y = 27.500000 a = 255 b = 5 c = 17
Here you have reversed the sequence of the floating-point arguments in the output by using the argument
index specification to select the argument for the format specifier explicitly. The integer values are also out-
put in a different sequence from the sequence in which the arguments appear so the names that are output do
not correspond with the variables.
To try out the use of "<" as the argument index specification, you could add the following statement to
the preceding fragment:
System.out.printf("%na = %3$d b = %<x c = %<o", a, b, c);
Search WWH ::




Custom Search