Java How to Convert Hexadecimal to Decimal Number
Use
Integer.parseInt(hexString, 16) in Java to convert a hexadecimal string to a decimal integer.Examples
Input"1A"
Output26
Input"FF"
Output255
Input"0"
Output0
How to Think About It
To convert hexadecimal to decimal, think of the hex string as a base-16 number. Each digit represents a value from 0 to 15. Java's
Integer.parseInt method can convert this string by specifying base 16, which automatically calculates the decimal value.Algorithm
1
Get the hexadecimal string input.2
Use a built-in method to parse the string as a base-16 number.3
Return or print the resulting decimal integer.Code
java
public class HexToDecimal { public static void main(String[] args) { String hex = "1A"; int decimal = Integer.parseInt(hex, 16); System.out.println(decimal); } }
Output
26
Dry Run
Let's trace converting "1A" to decimal using Integer.parseInt with radix 16.
1
Input Hex String
hex = "1A"
2
Parse Hex String
Integer.parseInt("1A", 16) converts '1A' to decimal 26
3
Output Decimal
decimal = 26
| Hex Digit | Decimal Value |
|---|---|
| 1 | 1 * 16 = 16 |
| A | 10 * 1 = 10 |
Why This Works
Step 1: Parsing with radix 16
The Integer.parseInt method takes the string and the base (16 for hex) to convert each digit correctly.
Step 2: Hex digits to decimal values
Each hex digit is converted to its decimal equivalent (0-15), then multiplied by powers of 16 based on position.
Step 3: Summing values
The method sums these values to produce the final decimal integer.
Alternative Approaches
Using Integer.valueOf
java
public class HexToDecimalAlt { public static void main(String[] args) { String hex = "FF"; int decimal = Integer.valueOf(hex, 16); System.out.println(decimal); } }
Works similarly to parseInt but returns an Integer object instead of primitive int.
Manual conversion with loop
java
public class HexToDecimalManual { public static void main(String[] args) { String hex = "1A"; int decimal = 0; for (int i = 0; i < hex.length(); i++) { char c = hex.charAt(i); int value = Character.digit(c, 16); decimal = decimal * 16 + value; } System.out.println(decimal); } }
Manually converts each digit; useful for learning but less concise.
Complexity: O(n) time, O(1) space
Time Complexity
Parsing processes each character once, so time grows linearly with string length.
Space Complexity
Uses constant extra space for variables; no additional data structures needed.
Which Approach is Fastest?
Using built-in Integer.parseInt is fastest and simplest; manual loops are slower and more error-prone.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Integer.parseInt(hex, 16) | O(n) | O(1) | Simple and fast conversion |
| Integer.valueOf(hex, 16) | O(n) | O(1) | When Integer object needed |
| Manual loop with Character.digit | O(n) | O(1) | Learning or custom parsing |
Always specify radix 16 when parsing hex strings to avoid errors.
Forgetting to specify radix 16 causes parseInt to treat the string as decimal, leading to errors.