Java Reference
In-Depth Information
Sample Run:
123456789012345678901234567890
763 658.75 Java Program.
Java Program.
763
658.75
658.75
763
Java Program.
num = 763
x = 658.75
str = Java Program.
Program No.
4
For the most part, the preceding output is self-explanatory. Let us consider some of these
statements. Notice that for each output statement, the output is right justified.
The statement in Line 4 outputs the first line of the sample run, which shows the column
positions. The statements in Lines 5 through 11 produce the remaining lines of output.
Let us consider the statement in Line 5, that is:
System.out.printf("%5d%7.2f%15s%n", num, x, str);
In this statement, the format string is "%5d%7.2f%15s%n" and the argument list is num , x ,
str .Thevalueof num is output in five columns, the value of x is output in seven columns
with two decimal places, and the value of str is output in 15 columns. Because only three
columns are needed to output the value of num , the first two columns are left blank. There is
no space between the format specifiers %5d and %7.2f ; therefore, the output of x begins at
column 6. Because only six columns are needed to output the value of x and the format
specifier %7.2f specifies seven columns, column 6 is left blank. Once again, there is no space
between the format specifiers %7.2f and %15s . The output of the object's value that str
points to begins at column 13. The reference variable str refers to the String object with
the value "Java Program." . Because the format specifier %15s specifies 15 columns and
only 13 columns are needed to output the string "Java Program." , the first two columns,
columns 13 and 14, are left blank. The format specifier %n positions the insertion point at the
beginning of the next line. The statements in Lines 6 and 7 work similarly.
Let us consider the statement in Line 8, that is:
System.out.printf("num = %5d%n", num);
Note that in this statement, the format string, "num ¼ %5d%n" , consists of a string and the
format specifier. This statement first outputs the string "num ¼ " , which requires six
columns. Then, starting at column 7, the value of num is output in five columns. Because
only three columns are needed to output the value of num , columns 7 and 8 are left blank.
If the number of columns specified in a format specifier is more than the number of
columns needed to output the result, then the (default) output is right justified. However,
strings such as names, typically, are left justified. To force the output to be left justified,
you can use the format specifier flag. If the flag is set to '-' , then the output of the result
is left justified.
Search WWH ::




Custom Search