This post will discuss how to convert an integer to a hex string in Java.

1. Using Integer.toHexString() method

A simple solution to convert an integer to a hex string is using the Integer.toHexString() method. It returns the string representation of the specified integer as an “unsigned” integer in base 16.

Download  Run Code

 
If uppercase letters are desired, you may call the String#toUpperCase() method on the result. Alternatively, you can use the toString() method of the Integer class which is overloaded to take a radix, and converts an integer to a string in the specified radix.

Download  Run Code

2. Using Long.toHexString() method

Both above methods fail for numbers greater than Integer.MAX_VALUE. That means it cannot produce a hexadecimal value greater than 0x7FFFFFFF. You can use Long.toHexString() method instead that works for numbers less than equal to Long.MAX_VALUE (i.e., 0x7FFFFFFFFFFFFFFF in hexadecimal).

Download  Run Code

 
Alternatively, you can use the Long.toString() method, which converts a long value to a string in the provided radix.

Download  Run Code

3. Using String.format() method

Finally, you can use the String.format() method that returns a formatted string using the specified format string and arguments. To format the argument as a hexadecimal integer, use the format string x.

Download  Run Code

 
To convert the hexadecimal value to upper-case, replace x with X.

Download  Run Code

 
To prepend the hexadecimal string with the radix indicator (0x or 0X), use the # flag.

Download  Run Code

That’s all about converting an integer to a hex String in Java.