Java Reference
In-Depth Information
Discussion
The
Formatter
class is patterned after C's
printf
routines. In fact,
PrintStream
and
PrintWriter
have convenience routines named
printf()
that simply delegate to the stream
or writer's
format()
method, which uses a default
Formatter
instance. Unlike in C,
however, Java is a strongly typed language, so invalid arguments will throw an exception
rather than generating gibberish.
The underlying
Formatter
class in
java.util
works on a
String
containing format codes.
For each item that you want to format, you put a format code. The format code consists of a
percent sign (
%
), optionally an argument number followed by a dollar sign (
$
), optionally a
field width or precision, and a format type (
d
for decimal integer, that is, an integer with no
decimal point,
f
for floating point, and so on). A simple use might look like the following:
System
.
out
.
printf
(
"%04d - the year of %f%n"
,
1956
,
Math
.
PI
);
As shown in
Figure 10-2
, the ā%04dā controls formatting of the year and the ā%2$fā con-
trols formatting of the value of PI.
[
35
]
Figure 10-2. Format codes examined
Many format codes are available;
Table 10-1
lists some of the more common ones. For a
complete description, refer to the javadoc for
java.util.Formatter
.