 # Java Program to convert hexadecimal number to decimal number

Here we are explaining how to write a java program to convert hexadecimal numbers to decimal numbers.

## What is the hexadecimal number?

The hexaDecimal number is the base sixteen number system. It includes the 0 to 9 and A to F.

Example:7A,5,8B etc.

The hexadecimal number 7A is equivalent to the decimal number 122.

## How to implement the java program to convert hexadecimal numbers to decimal numbers in java?

First, we have to declare the class HexToDec.Create an object of the scanner class as sc. Read the hexadecimal number from the user into the variable hex. Declare the string hs. Convert the string hex to uppercase.By using for loop take each character of the hex into the variable ch,n=hs.indexOf(ch),dec=16*dec+n.Repeat the loop until all characters of the string are checked. Then display the decimal number as dec.

## ALGORITHM

STEP 1: Declare the class HextToDec with a public modifier.

STEP 2: Open the main() to start the program, Java program execution starts with the main()

STEP 3:Create an object of the scanner class as sc.

STEP 4:Read the hexadecimal number from the user into the variable hex.

STEP 5: Read the decimal number from the user into the variable dec.

STEP 6: Declare the string hs="0123456789ABCDEF".

STEP 7: Convert the hexadecimal number to uppercase.

STEP 8: Set dec=0.To hold the decimal number.

STEP 9: By using `for loop` check i

STEP 10:Set ch=hext.charAt(i),n=hs.indexOf(ch),dec=16*dec+n.

STEP 11: Increment i by one and repeat step 9.

STEP 12: Display the decimal number as dec.

## Java Source Code

```                                          ```import java.util.Scanner;
public class HexToDec{
public static void main(String args[]){

Scanner sc = new Scanner(System.in);
String hex= sc.nextLine();

String hs = "0123456789ABCDEF";
hex = hex.toUpperCase();
int dec = 0;
for (int i = 0; i < hex.length(); i++)
{
char ch = hex.charAt(i);
int n = hs.indexOf(ch);
dec = 16*dec + n;
}
System.out.println("The decimal number "+dec);
}

}
```
```

## OUTPUT

```Enter the Hexadecimal number:7A
The decimal number 122```
VIEW ALL
VIEW ALL
##### OtherTutorials
VIEW ALL 