Displaying Hexadecimal Number in Java



You may sometimes need to print a number in hexadecimal format. To display an integer y in hexadecimal format, you may use the following.

System.out.println(String.format("%x", y));

This is a complete example showing how an integer is displayed in hexadecimal.

  1. /*
  2.   ReferenceDesigner.com Tutorial for beginners
  3.   Printing number in hexadecimal using println
  4.  */
  5. class hexa{
  6.  
  7. public static void main (String args[]) {
  8. int y =15;
  9.  
  10. // Print Numbers in Hexadecimal
  11.  
  12. System.out.println("15 in Hexa is " + String.format("%x", y));
  13. }
  14. }


If you compile and run this program, you will get following output.


16 in hexa is f




An integer is 4 bytes long. So you may want to pad the output with leading zeros. This can be done by replacing

System.out.println("15 in Hexa is " + String.format("%x", y));

with

System.out.println("15 in Hexa is " + String.format("%08x", y));

Which gives the output


16 in hexa is 000000f




Exercise

Write a program that will print numbers 0 to 255 in hexadecimal. It should have 2 digit and 1 digits number should be represented with leading zero.

Compare you solution with this one.

  1. /*
  2.   ReferenceDesigner.com Tutorial for beginners
  3.   Printing number in hexadecimal using println
  4.  */
  5. class hexa{
  6.  
  7. public static void main (String args[]) {
  8. int y =15;
  9.  
  10. // Print Numbers in Hexadecimal
  11.  
  12. System.out.println("15 in Hexa is " + String.format("%x", y));
  13. }
  14. }


You may also use

System.out.println( Integer.toHexString(i));

or System.out.printf("%02x", number);

to achieve the same result.

For example the numbe problem could be solved using.

for ( i=0; i<=255; i++)
System.out.printf("%02x\n", i);