## 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.

 `/*  ReferenceDesigner.com Tutorial for beginners  Printing number in hexadecimal using println */class hexa{  public static void main (String args[]) { int y =15;  // Print Numbers in Hexadecimal  System.out.println("15 in Hexa is " + String.format("%x", y)); }}`

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.

 `/*  ReferenceDesigner.com Tutorial for beginners  Printing number in hexadecimal using println */class hexa{  public static void main (String args[]) { int y =15;  // Print Numbers in Hexadecimal  System.out.println("15 in Hexa is " + String.format("%x", y)); }}`

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);