Java Reference
In-Depth Information
The <conversion> denotes how the output should be formatted. Its value depends on the data type of the
argument, which the format specifier refers to. It is mandatory.
There are two special format specifiers: "%%" and "%n" . The "%%" format specifier outputs "%" (a percent sign) and
"%n" outputs a platform-specific newline character. The following snippet of code demonstrates the use of these two
special format specifiers:
System.out.printf("Interest rate is 10%%.%nJohn%nDonna");
Interest rate is 10%.
John
Donna
You have not supplied any arguments to the printf() method in the code because these two special format
specifiers do not work on any arguments. Note the two newlines in the output that are generated by the two "%n"
format specifiers in the format string.
Referencing an Argument inside a Format Specifier
I have not covered the conversion part of the format specifier yet. For the discussion in this section, I will use 's' as
the conversion character for the format specifiers. The 's' conversion formats its argument as string. In its simplest
form, you can use "%s" as a format specifier. Let's consider the following snippet of code and its output:
System.out.printf("%s, %s, and %s", "Ken", "Lola", "Matt");
Ken, Lola, and Matt
A format specifier in a format string can refer to an argument in three ways:
Ordinary indexing
Explicit indexing
Relative indexing
Ordinary Indexing
When a format specifier does not specify an argument-index value (as in "%s" ), it is called ordinary indexing. In
ordinary indexing, the argument-index is determined by the index of the format specifier in the format string. The
first format specifier without argument-index has the index of 1, the second has the index of 2, and so on. The format
specifier with the index 1 refers to the first argument; the format specifier with the index 2 refers to the second
argument; and so on. Figure 13-1 shows the indices of the format specifiers and the arguments.
 
 
Search WWH ::




Custom Search