Recently (with the release of JDK 5), the printf( ) method was added to PrintStream. It
allows you to specify the precise format of the data to be written. The printf( ) method uses
the Formatter class (described in Chapter 18) to format data. It then writes this data to the
invoking stream. Although formatting can be done manually, by using Formatter directly,
printf( ) streamlines the process. It also parallels the C/C++ printf( ) function, which makes
it easy to convert existing C/C++ code into Java. Frankly, printf( ) is a much welcome addition
to the Java API because it greatly simplifies the output of formatted data to the console.
The printf( ) method has the following general forms:
PrintStream printf(String fmtString, Object ... args)
PrintStream printf(Locale loc, String fmtString, Object ... args)
The first version writes args to standard output in the format specified by fmtString, using the
default locale. The second lets you specify a locale. Both return the invoking PrintStream.
In general, printf( ) works in a manner similar to the format( ) method specified by
Formatter. The fmtString consists of two types of items. The first type is composed of
characters that are simply copied to the output buffer. The second type contains format
specifiers that define the way the subsequent arguments, specified by args, are displayed.
For complete information on formatting output, including a description of the format
specifiers, see the Formatter class in Chapter 18.
Because System.out is a PrintStream, you can call printf( ) on System.out. Thus, printf( )
can be used in place of println( ) when writing to the console whenever formatted output
is desired. For example, the following program uses printf( ) to output numeric values in
various formats. In the past, such formatting required a bit of work. With the addition of
printf( ), this now becomes an easy task.
// Demonstrate printf().
class PrintfDemo {
public static void main(String args[]) {
System.out.println("Here are some numeric values " +
"in different formats.\n");
System.out.printf("Various integer formats: ");
System.out.printf("%d %(d %+d %05d\n", 3, -3, 3, 3);
System.out.println();
System.out.printf("Default floating-point format: %f\n",
1234567.123);
System.out.printf("Floating-point with commas: %,f\n",
1234567.123);
System.out.printf("Negative floating-point default: %,f\n",
-1234567.123);
System.out.printf("Negative floating-point option: %,(f\n",
-1234567.123);
System.out.println();
System.out.printf("Line up positive and negative values:\n");
System.out.printf("% ,.2f\n% ,.2f\n",
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home