Convert Decimal to Hexadecimal in Java
Problem
Hexadecimal is base 16; it needs sixteen digit symbols, so it uses 0 to 9 followed by A to F for the values 10 to 15.
Given a non-negative integer, print its hexadecimal representation in uppercase.
Java Program
public class DecimalToHexadecimal {
public static void main(String[] args) {
int number = 3054;
String digits = "0123456789ABCDEF"; // index = digit value
if (number == 0) {
System.out.println("Hexadecimal of 0: 0");
return;
}
StringBuilder hex = new StringBuilder();
int n = number;
while (n > 0) {
hex.append(digits.charAt(n % 16)); // remainders 10 to 15 become A to F
n /= 16;
}
System.out.println("Hexadecimal of " + number + ": " + hex.reverse());
}
}Output
Core Logic
Dividing by 16 removes the lowest hex digit each time, and a 16-character lookup string turns each remainder into its symbol.
- 1
digitsholds"0123456789ABCDEF", sodigits.charAt(r)is the symbol for remainderr. - 2
n % 16gives the lowest digit's value, from 0 to 15. - 3
n /= 16moves on to the next digit. - 4The symbols are collected backwards and reversed at the end.
BEE.Key Point: The lookup string replaces an if chain for 10 to 15 — indexing into a table is a common trick for any digit-to-symbol mapping.
Why: Each step divides by 16, giving one iteration and one stored character per hex digit.
Key Concepts
Approach 2: Using Integer.toHexString() and String.format()
public class DecimalToHexadecimalBuiltIn {
public static void main(String[] args) {
int number = 3054;
System.out.println("toHexString: " + Integer.toHexString(number)); // lowercase digits
System.out.println("Uppercase: " + Integer.toHexString(number).toUpperCase());
System.out.println("Formatted: " + String.format("0x%04X", number)); // padded, with prefix
}
}
Output
Core Logic
The library offers two routes: toHexString for a plain conversion, and String.format when you need padding or a prefix.
- 1
Integer.toHexString(3054)returns lowercase"bee". - 2
.toUpperCase()gives the conventional uppercase form. - 3
String.format("0x%04X", 3054)pads to four digits and adds the0xprefix.
bee, BEE and 0x0BEE.Key Point: %x prints lowercase and %X uppercase — handy for colour codes like #0BEE00 or memory addresses.
Why: Each method still builds one character per hex digit.
Key Concepts
Interview Questions
How do you get uppercase hex digits?
Integer.toHexString(n).toUpperCase() or String.format("%X", n).
How many hex digits does a byte need?
Two, because each hex digit represents four bits.