Beruflich Dokumente
Kultur Dokumente
format
The System.out.print() and System.out.println() have some limitations, like controlling the number
of decimal points that will be written on screen in the case of a real number output, or the number
of spaces before the output. These limitations are addressed by System.out.printf() method or the
System.out.format() method. These methods use conversion characters. The conversion
character specifies the data type of the variable or literal that will be output and the location of the
output.
Here is a basic example:
int i = 461012;
System.out.format("The value of i is: %d%n", i);
The %d specifies that the single variable is a decimal integer. The %n is a platform-independent
newline character. The output is:
separator
You can use multiple flags, for example, "%,(.2f", to use group separators and enclose
negative numbers in parentheses.
< Formats the same value as the previous specification; for example, 159 9F
%d %<x prints the same number in decimal and hexadecimal
Note: Printf Date and Time Conversion Characters are intentionally not included in this manual.
The following program illustrates the use of System.out.printf():
1 import java.util.Calendar;
2 public class PrintFormat {
3 public static void main(String[] args) {
4
3
Lesson 7 – Displaying Output on Screen
The following is the output of the program except for the last two lines which is dependent on the
current computer date and time settings:
Percent: %
Boolean: true
Integer: 65
Character: M
Floating point: 95.669998
Double: 3.141593
Double: 3.14
Octal: 1733
Hexadecimal: 214
Local date: 05/08/12
Local time: 09:39:01
You may use System.out.format instead of System.out.printf and still have the same outpu
4
Lesson 7 – Displaying Output on Screen