Java Reference
In-Depth Information
Conversion Characters
Different conversion characters are used to format values of different data types. For example, 's' is used to format a
value as a string. The valid values for other parts in a format specifier are also determined by the conversion character
in the format specifier and the data type of the argument that the format specifier references. We can broadly classify
the formatting types based on data types in four categories:
General formatting
Character formatting
Numeric formatting
Many of the conversion characters have uppercase variants. For example, 'S' is the uppercase variant of 's' . The
uppercase variant converts the formatted output to uppercase as if output.toUpperCase() method was called, where
output is the reference to the formatted output string. The following statement and its output demonstrate the effect
of using the uppercase variant 'S' . Note that 's' produces "Ken" and 'S' produces "KEN" for the same input value
"Ken" .
Date/Time formatting
System.out.printf("%s and %<S", "Ken");
Ken and KEN
General Formatting
The general formatting can be used to format values of any data types. Table 13-4 has the list of conversions that are
available under the general formatting category.
Table 13-4. List of Conversion Characters for General Formatting
Conversion
Uppercase
Variant
Description
'b'
'B'
It produces “true” or “false” based on the value of the argument. It produces
“false” for a null argument and for a Boolean argument whose value is false.
Otherwise, it produces “true.”
'h'
'H'
It produces a string that is the hash code value in hexadecimal format of the
argument. If the argument is null , it produces “null.”
's'
'S'
It produces a string representation of the argument. If the argument is null ,
it produces a “null” string. If the argument implements the Formattable
interface, it invokes the formatTo() method on the argument and the returned
value is the result. If the argument does not implement the Formattable
interface, toString() method is invoked on the argument to get the result.
The general syntax for a format specifier for general formatting is
%<argument_index$><flags><width><.precision><conversion>
 
Search WWH ::




Custom Search