Java The Complete Reference, Seventh Edition

(Greg DeLong) #1
Theformat( )method accepts a wide variety of format specifiers, which are shown in
Table 18-12. Notice that many specifiers have both upper- and lowercase forms. When an
uppercase specifier is used, then letters are shown in uppercase. Otherwise, the upper- and
lowercase specifiers perform the same conversion. It is important to understand that Java
type-checks each format specifier against its corresponding argument. If the argument doesn’t
match, anIllegalFormatExceptionis thrown.
Once you have formatted a string, you can obtain it by callingtoString( ). For example,
continuing with the preceding example, the following statement obtains the formatted string
contained infmt:

String str = fmt.toString();

Of course, if you simply want to display the formatted string, there is no reason to first
assign it to aStringobject. When aFormatterobject is passed toprintln( ), for example, its
toString( )method is automatically called.
Here is a short program that puts together all of the pieces, showing how to create and
display a formatted string:

528 Part II: The Java Library


Format Specifier Conversion Applied
%a
%A

Floating-point hexadecimal

%b
%B

Boolean

%c Character
%d Decimal integer
%h
%H

Hash code of the argument

%e
%E

Scientific notation

%f Decimal floating-point
%g
%G

Uses%eor%f, whichever is shorter

%o Octal integer
%n Inserts a newline character
%s
%S

String

%t
%T

Time and date

%x
%X

Integer hexadecimal

%% Inserts a%sign

TABLE 18-12

The Format
Specifiers
Free download pdf