Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: What's the difference between format specifiers %x and %h?

Tags:

java

format

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
like image 348
Cristian Diaconescu Avatar asked Jan 03 '13 16:01

Cristian Diaconescu


3 Answers

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

like image 106
Stuart Golodetz Avatar answered Oct 20 '22 18:10

Stuart Golodetz


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... :)

like image 24
Veger Avatar answered Oct 20 '22 19:10

Veger


%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
like image 37
Peter Lawrey Avatar answered Oct 20 '22 18:10

Peter Lawrey