Java Reference
In-Depth Information
1.10.1. String Conversion and Formatting
The concatenation operator converts primitive values to strings using
the
toString
method of the corresponding wrapper class. This conversion
doesn't give you any control over the format of the resulting string.
Formatted conversion can be done with the
java.util.Formatter
class. A
Formatter
can write its output to a string, a file, or some other output
device. For convenience the
System.out.printf
method (for "print format-
ted") uses a formatter to write to
System.out
. Formatted output uses a
format string
together with a set of values to format. The format string
contains normal text together with
format specifiers
that tell the format-
ter how you want the subsequent values to be formatted. For example,
you can print the value of
Math.PI
to three decimal places using
System.out.printf("The value of Math.PI is %.3f %n",
Math.PI);
which prints
The value of Math.PI is 3.142
whereas using
println
and string concatenation you'd get:
The value of Math.PI is 3.141592653589793
A format specifier consists of at least two parts: it starts with a
%
char-
acter, and it ends with a conversion indicator. The conversion identifies
both the type of the value to format, and the basic form. For example,
%f
says to format a floating-point value in the usual decimal form, as used
for
Math.PI
above, whereas
%e
says to format a floating point value in sci-
entific notationfor example, 3.142e+00. Integer values can be format-