Java Reference
In-Depth Information
The
s
and
c
formats, for strings and characters, may include one number that specifies
the field width for outputting the value, such as
%15s
and
%2c
. If no number is given,
the value is output with no leading or trailing blank space.
When the value output does not fill the field width specified, blanks are added in
front of the value output. The output is then said to be
right justified
. If you add
a hyphen after the
%
, any extra blank space is placed after the value output, and the
output is said to be
left justified
. For example, the lines
s
and
c
right justified
left justified
double
value = 12.123;
System.out.printf("Start%8.2fEnd", value);
System.out.println();
System.out.printf("Start%-8.2fEnd", value);
System.out.println();
produce the following output. The first line has three spaces before the
12.12
and the
second has three spaces after the
12.12
.
Start 12.12End
Start12.12 End
more
arguments
So far we have used
printf
to output only one value. However,
printf
can
output any number of values. The first argument always is a string known as the
format string
, which can be followed with any number of additional arguments, each
of which is a value to output. The format string should include one format specifier,
such as
%6.2f
or
%s
, for each value output, and they should be in the same order as
the values to be output. For example,
format string
double
price = 19.8;
String name = "magic apple";
System.out.printf("$%6.2f for each %s.", price, name);
System.out.println();
System.out.println("Wow");
This code outputs the following:
$ 19.80 for each magic apple.
Wow
Note that the format string may contain text as well as format specifiers, and this text is
output along with the values of the other arguments to
printf
.
You can include line breaks in a format string. For example, the following two lines
new lines
System.out.printf("$%6.2f for each %s.", price, name);
System.out.println();
can be replaced by the single line below, which uses the escape sequence
\n
:
System.out.printf("$%6.2f for each %s.\n", price, name);