Java Reference
In-Depth Information
placed to the left, and spaces are added to the right. (The default is right alignment,
with spaces added to the left.) Thus, %-6s denotes a left-aligned string of width 6.
Table 3 Format Types
Code
Type
Example
d
123
Decimal integer
x
7B
Hexadecimal integer
o
173
Octal integer
f
12.30
Fixed floating-point
e
1.23e+1
Exponential floating-point
g
12.3
General floating-point (exponential
notation used for very large or very
small values)
s
Tax:
String
n
Platform-independent line end
You have already seen %5.2f: a floating-point number of width 5 and precision
2. The final specifier is %n , indicating a platform-independent line end. In
Windows, lines need to be terminated by two characters: a carriage return Ò\rÓ
and a newline Ò\nÓ . In other operating systems, a Ò\nÓ suffices. The %n format
emits the appropriate line terminators.
Moreover, this call to printf has two parameters. You can supply any number of
parameter values to the printf method. Of course, they must match the format
specifiers in the format string.
Table 4 Format Flags
Flag
Meaning
Example
-
Left alignment
1.23 followed by spaces
0
001.23
Show leading zeroes
+
+1.23
Show a plus sign for positive
numbers
(
(1.23)
Enclose negative numbers in
parentheses
,
12,300
Show decimal separators
1.23E+1
Ӽ
Convert letters to uppercase
168
169
The format method of the String class is similar to the printf method.
However, it returns a string instead of producing output. For example, the call
Search WWH ::




Custom Search