Java Reference
In-Depth Information
values and up to 15 decimal places for
double
values. Moreover, sometimes we would
like to align the output in certain columns. To format the output in a specific manner,
you can use the method
printf
.
A syntax to use the method
printf
to produce the output on the standard output
device is:
System.out.printf(formatString);
or:
System.out.printf(formatString, argumentList);
where
formatString
is a string specifying the format of the output and
argumentList
is a list of arguments. The
argumentList
is a list of arguments that consists of constant
values, variables, or expressions. If
argumentList
has more than one argument, then the
arguments are separated with commas.
For example, the statement:
System.out.printf("Hello there!");
//Line 1
consists of only the format string, and the statement:
System.out.printf("There are %.2f inches in %d centimeters.%n",
centimeters / 2.54, centimeters);
//Line 2
consists of both the format string and
argumentList
,where
centimeters
is a
variable of type
int
. Notice that the argument list consists of the expression
centimeters / 2.54
and the variable
centimeters
.Alsonoticethattheformat
string consists of the two expressions,
%.2f
and
%d
; these are called format
specifiers.Bydefau ,formatspec iersandtheargumen sin
argumentList
have a one-to-one correspondence. Here, the first format specifier
%.2f
is matched
with the first argument, which is the expression
centimeters / 2.54
.Itsaysto
output the value of the expression
centimeters / 2.54
to two decimal places. The
second format specifier
%d
is matched with the second argument, which is
centimeters
.Itsaystooutputthevalueof
centimeters
as a (decimal) integer.
(The format specifier
%n
positions the insertion point at the beginning of the next line.)
The output of the statement in Line 1 is:
Hello there!
Suppose that the value of
centimeters
is
150
. Now (to
14
decimal places):
centimeters / 2.54 = 150 / 2.54 = 59.05511811023622
Therefore, the output of the statement in Line 2 is:
There are 59.06 inches in 150 centimeters.
Notice that the value of the expression
centimeters / 2.54
is rounded and printed to
two decimal places.
Search WWH ::
Custom Search