Convert Hexadecimal to Decimal in Java

Topic

In this program, we will convert a number from hexadecimal (base 16) to decimal (base 10) using Java. Hexadecimal numbers use digits 0–9 and letters A–F (or a–f), where A stands for 10, B for 11, and so on up to F, which stands for 15.

This is a common conversion in computer science, especially in memory addresses, color codes, and low-level data handling. We'll use Java's built-in functionality to make it easier for beginners.

Examples

  • Input: 1A
    Output: 26
    Explanation: 1×16 + 10 = 26
  • Input: FF
    Output: 255
    Explanation: 15×16 + 15 = 255
  • Input: 0
    Output: 0
    Explanation: Zero in any base is zero.

Interviewer Expectations

Interviewers use this question to test your understanding of number systems, your ability to use Java's built-in methods (like Integer.parseInt()), and your overall problem-solving approach. They may also look at how you handle invalid input or lowercase vs uppercase characters.

Approach

We will read a hexadecimal number as a string and use Integer.parseInt(hex, 16) to convert it to decimal. The second argument 16 tells Java that the string is in base 16.

Dry Run

Input: 2F

  • 2 = 2 × 16 = 32
  • F = 15 × 1 = 15
  • Total = 32 + 15 = 47

Java Program

public class HexToDecimal {
  public static void main(String[] args) {
    String hex = "2F"; // Hexadecimal input
    int decimal = Integer.parseInt(hex, 16); // Convert hex to decimal
    System.out.println("Hexadecimal " + hex + " = Decimal " + decimal);
  }
}
Hexadecimal 2F = Decimal 47

Possible Followup Questions with Answers

1. What if the input is in lowercase (e.g., "ff")?

Java's Integer.parseInt() handles both uppercase and lowercase hexadecimal characters, so "FF" and "ff" will both return 255.

2. What if the input string is not a valid hexadecimal number?

The method Integer.parseInt() will throw a NumberFormatException. You can catch it using a try-catch block:

try {
  int decimal = Integer.parseInt("XYZ", 16);
} catch (NumberFormatException e) {
  System.out.println("Invalid hexadecimal input.");
}

3. Can we write our own logic without using Integer.parseInt()?

Yes! You can iterate through each character, multiply the accumulated result by 16, and add the value of the digit. This tests your logic handling skills.

int result = 0;
String hex = "2F";
for (int i = 0; i < hex.length(); i++) {
  char c = hex.charAt(i);
  int digit = Character.digit(c, 16);
  result = result * 16 + digit;
}

This manually mimics the built-in conversion process.


Comments

💬 Please keep your comment relevant and respectful. Avoid spamming, offensive language, or posting promotional/backlink content.
All comments are subject to moderation before being published.


Loading comments...