The java.text.Format
subclasses offer limited formatting capabilities and are
rather clumsy compared to the C language printf()
function, which provides a wide range of formatting options
combined with output operation.
To satisfy the demands of programmers for such a facility
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.
Furthermore, J2SE 5.0 added a printf()
method to the PrintStream
class (see Chapter
9). 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 so emulates the printf()
function in C.
In Chapter 9
we return to the java.util.Formatter
class 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
goes as
printf
(String format, Object... args)
The "..." indicates the varargs functionality (also
referred to as variable arity methods), 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 object references,
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