Java How to Convert Decimal to Hexadecimal
Integer.toHexString(decimalNumber), which returns the hexadecimal string representation.Examples
How to Think About It
Algorithm
Code
public class DecimalToHex { public static void main(String[] args) { int decimalNumber = 255; String hexString = Integer.toHexString(decimalNumber); System.out.println("Hexadecimal: " + hexString); } }
Dry Run
Let's trace converting decimal 255 to hexadecimal using Integer.toHexString.
Input decimal number
decimalNumber = 255
Convert to hexadecimal string
hexString = Integer.toHexString(255) -> "ff"
Print result
Output: Hexadecimal: ff
| Decimal Number | Hexadecimal String |
|---|---|
| 255 | ff |
Why This Works
Step 1: Using built-in method
The Integer.toHexString() method converts the decimal integer to its hexadecimal string form internally.
Step 2: Returns lowercase hex
The method returns the hexadecimal string in lowercase letters by default.
Step 3: Simple and efficient
This approach avoids manual division and remainder calculations, making the code clean and fast.
Alternative Approaches
public class DecimalToHexManual { public static void main(String[] args) { int decimal = 255; String hex = ""; char[] hexChars = "0123456789abcdef".toCharArray(); while (decimal > 0) { int remainder = decimal % 16; hex = hexChars[remainder] + hex; decimal /= 16; } System.out.println("Hexadecimal: " + (hex.isEmpty() ? "0" : hex)); } }
public class DecimalToHexFormat { public static void main(String[] args) { int decimal = 255; String hex = String.format("%x", decimal); System.out.println("Hexadecimal: " + hex); } }
Complexity: O(log n) time, O(log n) space
Time Complexity
Conversion depends on the number of digits in hexadecimal, which is proportional to log base 16 of the decimal number.
Space Complexity
The output string size grows with the number of hex digits, also proportional to log base 16 of the input.
Which Approach is Fastest?
Using built-in methods like Integer.toHexString() or String.format is faster and less error-prone than manual conversion.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Integer.toHexString() | O(log n) | O(log n) | Simple and fast conversion |
| Manual division and remainder | O(log n) | O(log n) | Learning and understanding conversion process |
| String.format | O(log n) | O(log n) | Concise formatting-based conversion |
Integer.toHexString() for quick and easy decimal to hexadecimal conversion in Java.toHexString returns a lowercase string and may expect uppercase letters.