Displaying Text with printf

A new feature of J2SE 5.0 is the System.out.printf method for displaying formatted datathe f in the name printf stands for "formatted." Figure 2.6 outputs the strings "Welcome to" and "Java Programming!" with System.out.printf.

Figure 2.6. Displaying multiple lines with method System.out.printf.

(This item is displayed on page 46 in the print version)

1 // Fig. 2.6: Welcome4.java 2 // Printing multiple lines in a dialog box. 3 4 public class Welcome4 5 { 6 // main method begins execution of Java application 7 public static void main( String args[] ) 8 { 9 System.out.printf( "%s %s ", 10 "Welcome to", "Java Programming!" ); 11 12 } // end method main 13 14 } // end class Welcome4  

Welcome to Java Programming!  

Lines 910

System.out.printf( "%s %s ", "Welcome to", "Java Programming!" );

call method System.out.printf to display the program's output. The method call specifies three arguments. When a method requires multiple arguments, the arguments are separated with commas (,)this is known as a comma-separated list.

Good Programming Practice 2.9

Place a space after each comma (,) in an argument list to make programs more readable.

Remember that all statements in Java end with a semicolon (;). Therefore, lines 910 represent only one statement. Java allows large statements to be split over many lines. However, you cannot split a statement in the middle of an identifier or in the middle of a string.

Common Programming Error 2.7

Splitting a statement in the middle of an identifier or a string is a syntax error.

Method printf's first argument is a format string that may consist of fixed text and format specifiers. Fixed text is output by printf just as it would be output by print or println. Each format specifier is a placeholder for a value and specifies the type of data to output. Format specifiers also may include optional formatting information.

Format specifiers begin with a percent sign (%) and are followed by a character that represents the data type. For example, the format specifier %s is a placeholder for a string. The format string in line 9 specifies that printf should output two strings and that each string should be followed by a newline character. At the first format specifier's position, printf substitutes the value of the first argument after the format string. At each subsequent format specifier's position, printf substitutes the value of the next argument in the argument list. So this example substitutes "Welcome to" for the first %s and "Java Programming!" for the second %s. The output shows that two lines of text were displayed.

We introduce various formatting features as they are needed in our examples. Chapters 28 presents the details of formatting output with printf.

Категории