The printf Method
The printf method is another way to format output. It
is based on the printf function of the C language.
System.out.printf(<format string>, <arg1>,
<arg2>, ..., <argn>);
The format string is a string that specifies how to
print out the output, and the args specify the values
that are to be printed out.
String name = "Foobear";
int n = 10;
double f = -132.5;
System.out.printf("%s %5d %6.2f", name, n, f);
will print out:
10 -132.50
with no end of line at the end.
Format Specifiers
The format string contains format specifiers. There is
a format specifier corresponding to each argument.
The first format specifier is used for the first
argument, the second for the second argument, and
so on. The format specifier specifies the how the
argument is to be interpreted (decimal, fixed-point,
exponential notation, string, character), and,
optionally, the field width, the precision, and the
Specifier Form
The general form of a format specifier is:
where – means to left justify, w is the field width, p is
the precision, and c is the conversion character.
Everything is optional except for the '%' and c.
Thus, a format specifier could be just
Conversion Characters
The most commonly used conversion characters are:
d – decimal (ordinary) integer
f – fixed point floating point number
e – exponential (scientific notation) floating point
g – general floating point (Java decides between
the previous two)
s – string
c - character
Optional Specifications
The optional parts of the format specifier are:
- left justify. Without this, the value is right
w – (an integer) field width. If the value printed
out takes fewer than w columns, it is padded with
p – (an integer) precision. The number of digits to
the right of the decimal point.
Added Text
The format string may also contain text, which is
printed out as is. This is used for labels, for $ (for
money), spacing, and new lines. The code %n will
output a new line character.
System.out.printf("You are owed $%6.2f. %n",