Java Reference
In-Depth Information
or more embedded format specifi ers . The args parameter is a variable-length argument that
contains a comma-separated list of data types that are written to the stream in the format
specifi ed by their corresponding format specifi er. Here is an example of a call to format :
6. PrintWriter out = new PrintWriter(System.out);
7. double d = 0.1/0.3;
8. String intro = ”d = “;
9. out.format(“%s%7.3f”, intro, d);
10. out.flush();
The PrintWriter on line 6 is chained to System.out , so it outputs characters to the con-
sole. The format specifi er on line 9 is ”%s%7.3f” . The ”s” denotes string conversion and
is associated with the intro argument. The ”f” denotes fl oating-point conversion and is
associated with the d argument. The 7.3 before the f denotes the width (7) and precision
(3) to output d in. Figure 4.9 shows how the format specifi er lines up with the arguments to
format .
FIGURE 4.9
Understanding format specifiers for the format method
format the second
argument, which is
a double
Out.format (“% s % 7.3f”, intro, d) j
format the first
argument, which is
a String
The output of the previous code is
d = 0.333
The double d has a width of 7, which includes the decimal point and two spaces preced-
ing it. Because the intro string already has a space after its equals sign, there are exactly
three spaces between the equals sign and the ”0.333” .
The syntax for a format specifi er is as follows:
%[argument_index$][flags][width][.precision]conversion
The argument_index is optional and denotes the position of the argument in the argu-
ment list. The flags value is optional and varies depending on the specifi er. The width
value is the minimum number of characters to output. For fl oating-point numbers, the pre-
cision value is the number of digits to write after the decimal point.
Java has over 15 format conversions, but the exam objectives only require you to know
the fi ve specifi ers shown in Table 4.2.
Search WWH ::




Custom Search