Professional Documents
Culture Documents
Where format is a string that consists of format specifiers. The items that
are to be displayed by the format specifiers must match the specifiers in
order, in number, and in exact data type. Common format specifiers are:
%c a character, for example ‘a’
%d a decimal integer, for example 200
%f a floating-point number, for example 45.4600
%s a string, for example “Java is cool”
Field width and precision can also be specified as well as adding comma
separators. These statements produce the following output:
System.out.println("-------+-------+-------+");
System.out.printf("%,8d%8s%8.1f\n", 1234, "Java", 34.56);
Output:
-------+-------+-------+
1,234 Java 34.6
By default, the output is right justified. You can place a minus sign (-) in the
specifier immediately after the per cent sign (%) to specify that the item will
be left justified within the specified field width. For example, these
statements:
System.out.println("-------+-------+-------+");
System.out.printf("%-,8d%-8s%-8.1f\n", 1234, "Java", 34.56);
The percent sign (%) denotes a specifier. To output a literal percent sign,
you must specify %% in the format string.
The printf method does not automatically supply a new line character (\n).
This can allow you to “build up” output one item at a time before proceeding
to the next line to be displayed.