Java Reference
In-Depth Information
Table 10-1. Formatter format codes
Code Meaning
c
Character (argument must be
char
or integral type containing valid character value).
d
“decimal int”—integer to be printed as a decimal (radix 10) with no decimal point (argument must
be integral type).
f
Floating-point value with decimal fraction (must be numeric); field width may be followed by
decimal point and fractional digit field width; e.g., 7.2f.
e
Floating-point value in scientific notation.
g
Floating-point value, as per f or e, depending on magnitude.
s
General format; if value is null, prints “null,” else if arg implements
Formattable
, format as per
arg.formatTo()
; else format as per
arg.toString()
.
t
Date codes; follow with secondary code. Common date codes are shown in
Table 10-2
. Argument
must be
long
,
Long
,
Calendar
, or
Date
.
n
Newline; insert the platform-dependent line ending character.
%
Insert a literal
%
character.
Note also that you may, but are not required to, put a “parameter order” number between the
%
and the format code. For example, in “%2$04d”, the “2$” means to format the
second
para-
meter, regardless of the order of the parameters. This is primarily useful with dates (see the
following example, where you need to format several different portions of the same
Date
or
Calendar
, or any time you want to format the same object more than once) and in interna-
tionalization, where different languages may require words to be in a different order within a
sentence.
Example 10-2. src/main/java/io/FormatterDemo.java
public
public class
class
FormatterDemo
FormatterDemo
{
public
public static
static
void
void
main
(
String
[]
args
) {
// The arguments to all these format methods consist of
// a format code String and 1 or more arguments.