6.2. The printf
Method¶
In Java, System.out refers to an object that implements
PrintStream methods, including print(Object), println(Object), and printf(String, Object…), for
standard output. The printf
method is particularly
interesting because it includes a varargs parameter
in its parameter list:
public PrintStream printf(String format, Object... args)
6.2.1. Format Strings and Specifiers¶
According to its documentation, printf
lets us print a
formatted string to output using the format string (format
)
and other arguments (args
) that are supplied when printf
is called. Here is a quick example that uses printf
and
the Person
class included in this chapter’s starter code:
public static void printSalary(Person person) {
String name = person.getName();
double salary = person.getSalary();
System.out.printf("The salary for %s is $%.2f.\n", name, salary);
} // printSalary
The argument supplied for format
is called a format
string, which is just a regular string that also satisfies the
Format String Syntax described in Formatter. Each %
character
in a format string denotes a format specifier for an argument
in the array referred to by args
. In the example above, %s
is the format specifier for name
, and %.2f
is the format
specifier for salary
.
To see how the format specifiers impact the output produced by the
calls to printf
in the printSalary
method shown
earlier, create and run a program similar to the one below:
public static void main(String[] args) {
Person susan = new Person("Susan", 120000.0);
Person bob = new Person("Bob", 115300.5);
printSalary(susan); // The salary for Susan is $120000.00.
printSalary(bob); // The salary for Bob is $115300.50.
} // main
6.2.2. Use of Varargs¶
At runtime, printf
replaces each format specifier in its
format string with a formatted version of its corresponding argument.
Since the args
parameter is a varargs parameter, the
corresponding arguments do need to be manually placed into an array
before calling printf
. Although Object...
technically
denotes that zero or more Object
references can be supplied,
printf
considers it an error when args.length
does not
equal the number of format specifiers in the format string.
6.2.3. A Few Format Specifier Examples¶
The table below summarizes a few of the format specifiers that can be used in format strings, including the ones used in the examples:
Format Specifier |
Description |
---|---|
|
|
|
|
|
|
|
|
For a complete list of possible format specifiers, refer to the Format String Syntax section in Formatter.