How to Convert Hexadecimal to Decimal in Java

There are two methods to convert Hexadecimal to Decimal:

  • Using parseInt() method
  • Using user-defined logic

Using Integer.parseInt() method

It is a static method of theInteger wrapper class. The Integer.parseInt() method converts string to int with given radix. The signature of the method is given below:

public static int parseInt(String hexdecnum,int radix)

Where hexdecnumis the string that you want to convert.


In the following example, we have taken a variable hexavalof type String and assigned“E” to it.decimal is a variable of type int which stores the converted value of the variable hexaval.parseInt() is the static method of Integer wrapper class which belongs to the java.lang package. It parses two arguments: first is hexaval which we want to convert into decimal and thesecond is radix i.e. 16. The println statement prints the converted decimal value of “E”.


Using user defined logic

You can also convert Hexadecimal to Decimal by defining your own logic.


In the following example, we have taken twoStringvariableshexdec and hex and initialize “E3” and “123456789ABCDEF” to it respectively. We have taken an integer variable decimal and assign 0 to it.Here we will use for loop.

The hexdec.length() method returns the length of the String i.e. 1.The charAt() method of String class returns the character at ithposition and stores the character into the variable ch.The hex.indexOf()method of String class returns the indexvalue of the characterfrom the specified string. Let’s see how the loop will execute.

For first iteration:


i=0                                                          //initial value

0<hexdec.length()                          //condition true

ch=hexdec.charAt(0)                     //returns ‘E’

in=hex.indexOf(E)                           //returns index value of E i.e. 14

decimal=16*0+14                             //updated value of decimal is 14

i++                                                          //i increment by 1 i.e. the value of i is 1

For second iteration:



1<hexdec.length()                          //condition true

ch=hexdec.charAt(1)                     //returns ‘3’

in=hex.indexOf(3)                           //returns index value of 3 i.e. 3

decimal=16*14+3                             //updated value of decimal is 227

i++                                                          //i increment by 1 i.e. the value of i is 2

Forthird iteration:


2<hexdec.length()                          //condition false

Hence the third iteration will not execute the loop. The next statement out of the loop will be execute. The println statement prints the converted decimal value of “E3” i.e.227.


Pin It on Pinterest

Share This