Java Program for Hexadecimal to Decimal Conversion

Last Updated : 7 Aug, 2026

A hexadecimal number is a number represented in the base-16 number system, which uses digits 0–9 and letters A–F to represent values from 0 to 15. The decimal number system is a base-10 number system that uses digits 0–9.

  • Each hexadecimal digit is processed from left to right.
  • The method also handles lowercase hexadecimal letters such as a–f.

Illustration:

Input : 1AB
Output: 427

Input : 1A
Output: 26

hexaTodeci

Approach to Convert Hexadecimal to Decimal

To convert hexadecimal to decimal:

  • Start from the rightmost hexadecimal digit.
  • Convert each digit or letter into its decimal value.
  • Multiply the value by the corresponding power of 16.
  • Add all the values to get the decimal number.
  • Repeat until all hexadecimal digits are processed.

Example:Program to Convert Hexadecimal to Decimal

Java
class GFG {

    static int hexadecimalToDecimal(String hex) {
        int decimal = 0;

        for (int i = 0; i < hex.length(); i++) {
            char ch = Character.toUpperCase(hex.charAt(i));
            int value;

            if (ch >= '0' && ch <= '9') {
                value = ch - '0';
            } else if (ch >= 'A' && ch <= 'F') {
                value = ch - 'A' + 10;
            } else {
                throw new IllegalArgumentException("Invalid hexadecimal number");
            }

            decimal = decimal * 16 + value;
        }

        return decimal;
    }

    public static void main(String[] args) {
        String hex = "1AB";

        int decimal = hexadecimalToDecimal(hex);

        System.out.println("Decimal equivalent of " + hex + " is: " + decimal);
    }
}

Output
Decimal equivalent of 1AB is: 427

Explanation: The hexadecimalToDecimal() method processes each hexadecimal digit from left to right. Numeric characters are converted directly, while A–F are converted to values 10–15. The decimal result is updated using decimal = decimal * 16 + value. For 1AB, the calculation becomes ((1 × 16) + 10) × 16 + 11 = 427.

Comment