Java Reference
In-Depth Information
5.11.2 The
printf()
method
The
Format
subclasses discussed above clearly have limited formatting capabil-
ities and are rather clumsy to implement. Also, the two-step process of formatting
a string and then sending it to where it is needed can be rather tedious, especially
for output to the console or to a file. Those with experience in the C language
have missed the
printf()
function, which offers a wide range of formatting
options and also combines formatting and output.
To satisfy the demands of such programmers and to facilitate the porting of
C programs to Java, J2SE 5.0 comes with the class
java.util.Formatter
,
which can both format numerical output into a string and send the string to a file
or other destination (we discuss I/O in Chapter 9). Numerical values are formatted
according to format
specifiers
like those for the
printf()
function in C.
In fact, J2SE 5.0 went a step further and actually added a
printf()
method to the
PrintStream
class (see Chapter 9), of which
System.out
and
System.err
are instances. So now you can use
System.out.printf()
to
send formatted numerical output to the console. It uses a
java.util.
Formatter
object internally and closely emulates the
printf()
function in C.
In Section 9.4.2 we return to the
java.util.Formatter
class so that we
can discuss it in the context of Java I/O. Here we introduce the
printf()
method
so that you can begin to take advantage of it.
The simplest of the overloaded versions of the method is
printf (String format, Object...args)
The
“...
„
indicates the varargs functionality, which we noted in Chapter 1
was introduced with J2SE 5.0. It allows a method to accept a variable number of
arguments. We note that the arguments can be primitives as well as objects, e.g.
the wrappers for the primitives.
The
format
argument is a string in which you embed specifier substrings
that indicate how the arguments appear in the output. For example,
double pi
=
Math.PI;
System.out.printf ("pi = %5.3f%n", pi);
results in the console output
pi = 3.142
The format string includes the specifier
“%5.3f
„
that is applied to the argument.
The
%
sign signals a specifier. The
width
value 5 requires at least five characters
for the number, the
precision
value 3 requires three places in the fraction, and
the
conversion
symbol
f
indicates a decimal representation of a floating-point
number.
A specifier needs at least the conversion character, of which there are several
besides
f
. Some of the other conversions include
Search WWH ::
Custom Search