Java Reference
In-Depth Information
finally {
if (fm != null) {
fm.close();
}
}
The format() method of the Formatter class is overloaded. Its declarations are as follows.
Formatter format(String format, Object... args)
Formatter format(Locale l, String format, Object... args)
The first version of the format() method uses the default locale for formatting. The second version allows
you to specify a locale. The format() / printf() method of the PrintStream class and the format() method of the
String class provide the same two versions of the format() method, which accept the same types of arguments.
This discussion of the format() method of the Formatter class equally applies to these convenience methods in the
PrintStream and String classes.
The Formatter class uses the locale-specific formatting whenever it is applicable. For example, if you want to
format a decimal number, say 12.89, the number is formatted as 12,89 (notice a comma between 12 and 89) in
France whereas it is formatted as 12.89 (notice a dot between 12 and 89) in the United States. The locale argument of
the format() method is used to format text in a locale-specific format. The following snippet of code demonstrates
the effects of locale-specific formatting. Note the difference in the formatted output for US and France for the same
input values.
System.out.printf(Locale.US, "In US: %1$.2f %n", 12.89);
System.out.printf(Locale.FRANCE, "In France: %1$.2f %n", 12.89);
Date dt = new Date();
System.out.printf(Locale.US, "In US: %tA %n", dt);
System.out.printf(Locale.FRANCE, "In France: %tA %n", dt);
In US: 12.89
In France: 12,89
In US: Friday
In France: vendredi
The Details
Formatting data using a Formatter requires two types of inputs:
A format string
A list of values
The format string is the template that defines how the output will look. It contains zero or more occurrences of
fixed texts and zero or more embedded format specifiers. No formatting is applied to the fixed text.
A format specifier serves two purposes. It acts as a placeholder for the formatted data inside the format string and
it specifies how the data should be formatted.
Let's consider the following example. Suppose you want to print a text with the birth date of a person. The
following is an example of such a text:
January 16, 1970 is John's birth day.
 
Search WWH ::




Custom Search