Java Reference
In-Depth Information
Table 4.6
Common Format Specifiers
Specifier
Result
Integer
%d
Integer, right-aligned, 8-space-wide field
%8d
Integer, left-aligned, 6-space-wide field
% 6d
Floating-point number
%f
Floating-point number, right-aligned, 12-space-wide field
%12f
Floating-point number, rounded to nearest hundredth
%.2f
Floating-point number, rounded to nearest thousandth, 16-space-wide field
%16.3f
String
%s
String, right-aligned, 8-space-wide field
%8s
String, left-aligned, 9-space-wide field
% 9s
As a comprehensive example, suppose that the following variables have been
declared to represent information about a student:
int score = 87;
double gpa = 3.18652;
String name = "Jessica";
The following code sample prints the preceding variables with several format
specifiers:
System.out.printf("student name: %10s\n", name);
System.out.printf("exam score : %10d\n", score);
System.out.printf("GPA : %10.2f\n", gpa);
The code produces the following output:
student name: Jessica
exam score : 87
GPA : 3.19
The three values line up on their right edge, because we print all of them with a
width of 10. The printf method makes it easy to line up values in columns in this
way. Notice that the student's GPA rounds to 3.19, because of the 2 in that variable's
format specifier. The specifier 10.2 makes the value fit into an area 10 characters
wide with exactly 2 digits after the decimal point.
Let's return to our multiplication table example. Now that we know about printf ,
we can print the table with right-aligned numbers relatively easily. We'll right-align
the numbers into fields of width 5:
for (int i = 1; i <= 10; i++) {
for (int j = 1; j <= 10; j++) {
 
Search WWH ::




Custom Search