Java Reference
In-Depth Information
ted by
%d
for normal decimal, or
%x
for hexadecimal form. A string can
be formatted by
%s
.
The
%n
conversion causes insertion of the correct line-separator char-
acter, something that
println
does automatically for you. The line-sep-
arator depends on the current platform and may not be a simple
\n
(newline) character. If you are familiar with
printf
from the
C
program-
ming language you need to get used to using
%n
instead of
\n
.
A format specifier can provide additional formatting information. You
can provide a
width
that indicates the minimum number of characters to
printuseful for aligning columns of data. If the formatted value has few-
er characters than the width, it is padded with spaces to fit the minim-
um size. This lets you align values easily. Some conversions also allow a
precision
value to be given, which is written as
.
followed by a non-neg-
ative number. For floating-point values using
%f
the precision indicates
how many decimal places to round toin the example above the value of
Math.PI
is rounded to 3 decimal places because of the
.3
in the format
specifier. If both a width and precision are given they are written in the
form
width.precision
. Additional flags in the format specifier can, among
other things, request zero padding (instead of spaces) or left-justifica-
tion (the default is right justification).
Formatted output is covered in detail in
Chapter 22
.
Exercise 1.13
: Rewrite the
ImprovedFibonacci
program using
printf
in-
stead of
println
.