Java Reference
In-Depth Information
The general syntax for a format specifier for integral number formatting is as follows:
%<argument_index$><flags><width><conversion>
Note that precision part in a format specifier is not applicable to integral number formatting. The following
snippet of code demonstrates the use of the
'd'
conversion with various flags to format integers:
System.out.printf("'%d' %n", 1969);
System.out.printf("'%6d' %n", 1969);
System.out.printf("'%-6d' %n", 1969);
System.out.printf("'%06d' %n", 1969);
System.out.printf("'%(d' %n", 1969);
System.out.printf("'%(d' %n", -1969);
System.out.printf("'% d' %n", 1969);
System.out.printf("'% d' %n", -1969);
System.out.printf("'%+d' %n", 1969);
System.out.printf("'%+d' %n", -1969);
'1969'
' 1969'
'1969 '
'001969'
'1969'
'(1969)'
' 1969'
'-1969'
'+1969'
'-1969'
When conversions
'o'
and
'x'
are used with a negative argument of
byte
,
Byte
,
short
,
Short
,
int
,
Integer
,
long
, and
Long
data types, the argument value is first converted to an unsigned number by adding a number
2N
to
it, where
N
is the number of bits used to represent the value of the data type of the argument. For example, if the
argument data type is
byte
, which takes 8 bits to store the value, the argument value of
-X
will be converted to a
positive value of
-X + 256
by adding 256 to it and the result contain the base-8 or base-16 equivalent of the value
-X + 256
. The conversions
'o'
and
'x'
do not transform the negative argument value to an unsigned value for a
BigInteger
argument type. Consider the following snippet of code and the output:
byte b1 = 9;
byte b2 = -9;
System.out.printf("%o %n", b1);
System.out.printf("%o %n", b2);
11
367
The conversion
'o'
outputs the base-8 integer 11 for a positive decimal integer 9. However, when a negative
decimal integer -9 is used with the
'o'
conversion, -9 is converted to a positive number
-9 + 256
(
=247
). The final
output contains
367
, which is the base-8 equivalent of the decimal
247
.