Java Reference
In-Depth Information
A much easier way to print values aligned in fixed-width fields is to use the
System.out.printf command. The printf method accepts a specially written
String called a format string that specifies the general appearance of the output, fol-
lowed by any parameters to be included in the output:
System.out.printf(<format string>, <parameter>, ..., <parameter>);
A format string is like a normal String, except that it can contain placeholders
called format specifiers that allow you to specify a location where a variable's value
should be inserted, along with the format you'd like to give that value. Format speci-
fiers begin with a % sign and end with a letter specifying the kind of value, such as d
for decimal integers ( int ) or f for floating-point numbers (real numbers of type
double ). Consider the following printf statement:
int x = 38, y = 152;
System.out.printf("location: (%d, %d)\n", x, y);
This statement produces the following output:
location: (38, 152)
The %d is not actually printed but is instead replaced with the corresponding parame-
ter written after the format string. The number of format specifiers in the format string
must match the number of parameters that follow it. The first specifier will be replaced
by the first parameter, the second specifier by the second parameter, and so on.
System.out.printf is unusual because it can accept a varying number of parameters.
The printf command is like System.out.print in that it doesn't move to a new
line unless you explicitly tell it to do so. Notice that in the previous code we ended
our format string with \n to complete the line of output.
Since a format specifier uses % as a special character, if you want to print an actual
% sign in a printf statement, instead write two % characters in a row. For example:
int score = 87;
System.out.printf("You got %d%% on the exam!\n", score);
The code produces the following output:
You got 87% on the exam!
A format specifier can contain information after its % sign to specify the width, pre-
cision, and alignment of the value being printed. For example, %8d specifies an integer
right-aligned in an 8-space-wide area, and %12.4f specifies a double value right-
aligned in a 12-space-wide area, rounded to four digits past the decimal point. Table 4.6
lists some common format specifiers that you may wish to use in your programs.
 
Search WWH ::




Custom Search