- 2.1 Introduction
- 2.2 Your First Program in Java: Printing a Line of Text
- 2.3 Modifying Your First Java Program
- 2.4 Displaying Text with printf
- 2.5 Another Application: Adding Integers
- 2.6 Memory Concepts
- 2.7 Arithmetic
- 2.8 Decision Making: Equality and Relational Operators
- 2.9 Wrap-Up
- Summary
- Self-Review Exercises
- Answers to Self-Review Exercises
- Exercises
- Making a Difference
2.4 Displaying Text with printf
The System.out.printf method (f means "formatted") displays formatted data. Figure 2.6 uses this method to output the strings "Welcome to" and "Java Programming!". Lines 9–10
Fig 2.6. Displaying multiple lines with method System.out.printf.
1// Fig. 2.6: Welcome4.java
2// Displaying multiple lines with method System.out.printf.
3 4public class
Welcome4 5 { 6// main method begins execution of Java application
7public static void
main( String[] args ) 8 { 9System.out.printf( "%s\n%s\n",
10"Welcome to", "Java Programming!" );
11 }// end method main
12 }// end class Welcome4
System.out.printf( |
call method System.out.printf to display the program's output. The method call specifies three arguments. When a method requires multiple arguments, they're placed in a comma-separated list.
Lines 9–10 represent only one statement. Java allows large statements to be split over many lines. We indent line 10 to indicate that it's a continuation of line 9.
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 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 (%) 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, each 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. 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 are displayed.
We introduce various formatting features as they're needed in our examples. Appendix G presents the details of formatting output with printf.