Looking at the specification page, I see that %h
calls into Integer.toHexString(), but I can't find any practical difference between the two specifiers.
Can you give an example where using the to specifiers on the same input yields different results?
System.out.println(String.format("%1$h %1$x", 123));
This prints
7b 7b
The %h
specifier invokes hashCode
on its argument (provided it is not null
, when you get "null"), whereas the %x
specifier just formats its argument as a hexadecimal integer. This makes a major difference if the thing being formatted isn't an integer. See the examples here:
http://developer.android.com/reference/java/util/Formatter.html
In particular, the fact that you get the same results for integers is a result of the fact that Integer.hashCode
returns the integer itself:
http://docs.oracle.com/javase/6/docs/api/java/lang/Integer.html#hashCode%28%29
The page you provided states:
'h' If the argument arg is null, then the result is "null". Otherwise, the result is obtained by invoking Integer.toHexString(arg.hashCode()).
and
'x' The result is formatted as a hexadecimal integer
So %h
prints null
if the provided object was null
, otherwise %h
prints the hash code of the object. Whereas %x
prints the hex-value of the provided int
value.
Edit: as pointed out in the comments: if no value for %x
is given an IllegalFormatConversionException
is thrown, as stated here:
If a format specifier contains a conversion character that is not applicable to the corresponding argument, then an IllegalFormatConversionException will be thrown.
So basically, you'd just needed to read the page you provided... :)
%h
prints the hashcode of an object in hexidecimal.
%x
prints a number in hexidecimal.
For Integer
the hashCode and the value are the same. For Long
the value and the hashCode can be different.
System.out.printf("%h%n", "hello world");
System.out.printf("%h%n", 0x1234567890L);
System.out.printf("%x%n", 0x1234567890L);
prints
6aefe2c4
34567882
1234567890
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With