Java Reference
In-Depth Information
22.1.
Formatter
The
Formatter
class allows you to control the way in which primitive val-
ues and objects are represented as text. The common way to represent
objects or values as text is to convert the object or value to a string, us-
ing either the
toString
method of the object or the
toString
method of the
appropriate wrapper class. This is often done implicitly, either through
use of string concatenation or by invoking a particular overload of the
PrintStream
or
PrintWriterprint
methods. This is easy and convenient, but
it doesn't give you any control over the exact form of the string. For ex-
ample, if you invoke
System.out.println("The value of Math.PI is " + Math.PI);
the output is
The value of Math.PI is 3.141592653589793
This is correct and informative, but it might provide more detail than the
reader really needs to see, or more than you have room to show. Using
a formatter you can control the format of the converted text, such as re-
stricting the value to only three decimal places, or padding the converted
string with spaces so that it occupies a minimum width regardless of the
actual value being converted. All of these operations are possible starting
from the result of
toString
, but it is much easier to have a formatter do
it for you.
The primary method of a
Formatter
object is the
format
method. In its
simplest form it takes a
format string
followed by a sequence of argu-
ments, which are the objects and values you want to format. For con-
venience the
PrintStream
and
PrintWriter
classes provide a
printf
meth-
od (for "print formatted") that takes the same arguments as
format
and
passes them through to an associated
Formatter
instance. We use the
Sys-
tem.out.printf
method to demonstrate how format strings are used.