Java convert hex to decimal

Let’s learn java convert hex to decimal.

Java convert hex to decimal

Java program that converts a hexadecimal number to a decimal number is one of the frequently asked java program interview question.

In hexadecimal to decimal java conversion we are using Integer.parseInt() method. Integer.parseInt() method parses string argument as a signed integer in the radix specified by the second argument. Here’s the syntax.

public static int parseInt(String s, int radix) throws NumberFormatException

Let’s see java program.

public class ConvertHexToDecimal
{
   public static void main(String[] args)
   {
      String strHex = "b";
      int decimal = Integer.parseInt(strHex, 16);
      System.out.println("Decimal number : " + decimal);
   }
}


Output:

Decimal number : 11


Hexadecimal to decimal java user input

Meanwhile to we can convert hexadecimal to decimal based on user input. For this we need nextLine() method of Scanner class. This user input string is stored in String variable ‘strHexNumber’.

Logic to convert a hexadecimal to a decimal number is same as above java program. Now let’s see hexadecimal to decimal java user input.

import java.util.Scanner;
public class HexToDecimalDemo 
{
   public static void main(String[] args) 
   {
      Scanner sc = new Scanner(System.in);
      System.out.println("Please enter hexadecimal number: ");
      String strHexNumber = sc.nextLine();    
      // converting hexadecimal to decimal by passing base 16 
      int decimalNumber = Integer.parseInt(strHexNumber, 16);
      System.out.println("Converting hexadecimal to decimal: " + decimalNumber);
      sc.close();
   }
}


Output:

Please enter hexadecimal number: 6A
Converting hexadecimal to decimal: 106


Similarly we can convert hexadecimal to decimal java using user defined method.

public class HexaToDecimal
{
   public static int convertHexadecimal(String strHex)
   {
      String Hexadecimal = "0123456789ABCDEF";
      strHex = strHex.toUpperCase();
      int value = 0;
      for(int a = 0; a < strHex.length(); a++)
      {
         char ch = strHex.charAt(a);
         int d = Hexadecimal.indexOf(ch);
         value = 16 * value + d;
      }
      return value;
   }
   public static void main(String[] args)
   {
      System.out.println("Decimal value of b is : " + convertHexadecimal("b"));
      System.out.println("Decimal value of d is : " + convertHexadecimal("d"));
      System.out.println("Decimal value of 151 is : " + convertHexadecimal("151"));
   }
}


Output:

java convert hex to decimal

Also read – garbage collection in java