Java Reference
In-Depth Information
%n
Although it is legal to use the escape sequence
\n
to indicate a line break in a format
string, it is preferable to use
%n
. Exactly what happens when a
\n
is output can be
system dependent, whereas
%n
should always mean a simple new line on any system. So
our last line of code would be a little more robust if rewritten using
%n
as follows:
System.out.printf("$%6.2f for each %s.%n", price, name);
Many of the details we have discussed about
printf
are illustrated in the program
given in Display 2.2 .
TIP: Formatting Monetary Amounts with
printf
A good format specifier for outputting an amount of money stored as a value of type
double
(or other floating-point value) is
%.2f
. It says to include exactly two digits
after the decimal point and to use the smallest field width that the value will fit into.
For example,
double
price = 19.99;
System.out.printf("The price is $%.2f each.", price);
produces the following output:
■
The price is $19.99 each.
Display 2.2
The
printf
Method
(part 1 of 2)
1
public class
PrintfDemo
2 {
3
public static void
main(String[] args)
4 {
5 String aString = "abc";
6 System.out.println("String output:");
7 System.out.println("START1234567890");
8 System.out.printf("START%sEND %n", aString);
9 System.out.printf("START%4sEND %n", aString);
10 System.out.printf("START%2sEND %n", aString);
11 System.out.println();
12
char
oneCharacter = 'Z';
13 System.out.println("Character output:");
14 System.out.println("START1234567890");
15 System.out.printf("START%cEND %n", oneCharacter);
16 System.out.printf("START%4cEND %n", oneCharacter);
17 System.out.println();
(continued)