Java The Complete Reference, Seventh Edition

(Greg DeLong) #1

Chapter 19: Input/Output: Exploring java.io 575


Recently (with the release of JDK 5), theprintf( )method was added toPrintStream. It
allows you to specify the precise format of the data to be written. Theprintf( )method uses
theFormatterclass (described in Chapter 18) to format data. It then writes this data to the
invoking stream. Although formatting can be done manually, by usingFormatterdirectly,
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.
Theprintf( )method has the following general forms:


PrintStream printf(StringfmtString, Object ...args)

PrintStream printf(Localeloc, StringfmtString, Object ...args)

The first version writesargsto standard output in the format specified byfmtString,using the
default locale. The second lets you specify a locale. Both return the invokingPrintStream.
In general,printf( )works in a manner similar to theformat( )method specified by
Formatter. ThefmtStringconsists 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 byargs,are displayed.
For complete information on formatting output, including a description of the format
specifiers, see theFormatterclass in Chapter 18.
BecauseSystem.outis aPrintStream, you can callprintf( )onSystem.out. Thus,printf( )
can be used in place ofprintln( )when writing to the console whenever formatted output
is desired. For example, the following program usesprintf( )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",
Free download pdf