Java Reference
In-Depth Information
Display 2.2
The
printf
Method
(part 2 of 2)
18
double
d = 12345.123456789;
19 System.out.println("Floating-point output:");
20 System.out.println("START1234567890");
21 System.out.printf("START%fEND %n", d);
22 System.out.printf("START%.4fEND %n", d);
23 System.out.printf("START%.2fEND %n", d);
24 System.out.printf("START%12.4fEND %n", d);
25 System.out.printf("START%eEND %n", d);
26 System.out.printf("START%12.5eEND %n", d);
27 }
28 }
Sample Dialogue
String output:
START1234567890
STARTabcEND
START abcEND
STARTabcEND
The value is always output. If the specified field width
is too small, extra space is taken.
Character output:
START1234567890
STARTZEND
START ZEND
Floating-point output:
START1234567890
START12345.123457END
START12345.1235END
START12345.12END
START 12345.1235END
START1.234512e+04END
START 1.23451e+04END
Note that the output is rounded, not
truncated, when digits are discarded.
TIP: Legacy Code
Some code is so expensive to replace, it is used even if it is “old fashioned” or otherwise
less than ideal. This sort of code is called
legacy code
. One approach to legacy code
is to translate it into a more modern language. The Java method
printf
is essentially
the same as a function
1
in the C language that is also named
printf
. This was done
intentionally so that it would be easier to translate C code into Java code.
legacy code
■
1
Methods are called
functions
in the C and C++ languages.