Write a Java Program to **convert a binary number to its corresponding decimal** representation.

**Example:**

1 2 3 4 5 | Input: 101 Output: 5 Input: 1111 Output: 15 |

The standard way of converting any binary number to its decimal representation is to **multiply each of the binary digits with the value of 2 raised to the power to its index** (the position from right – 1 ) and sum them up.

Refer to the picture given below for clear understanding.

Let’s implement the same in Java.

## Convert Binary to Decimal in Java using While Loop

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner in=new Scanner(System.in); System.out.println("Enter a Binary"); int binary = in.nextInt(); int lastDigit, decimal=0, i=0; while(binary>0){ lastDigit = binary%10; //remainder is the last digit //Add by multiplying the last digit with the 2^i decimal += Math.pow(2,i) * lastDigit; binary = binary/10; //update binary by removing the last digit i++; //Increment exponent ('i') } System.out.println("Decimal: "+decimal); } } |

**Output**

`Enter a Binary`

101

Decimal: 5

## Convert Binary to Decimal in Java using Recursion

The approach is the same as the above method but in a recursive way. We need to **extract the last digit from the received binary number** ( only when it is not a single-digit) on each recursive call.

Then we need to **multiply it with its corresponding value of 2 raised to the power its position** in the original binary number from the right and sum it up with the next recursive call result.

we need to eliminate the last digit from the binary number on the next recursive call.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner in=new Scanner(System.in); System.out.println("Enter a Binary"); int binary = in.nextInt(); System.out.println("Decimal: "+binToDec(binary, 0)); } //'i' represents the nth recursive call as well as //nth digit from left, so it can be used as an exponent private static int binToDec(int bin, int i){ if(bin == 0 || bin == 1) return (int)Math.pow(2,i)*bin; int lastDigit = bin%10; return (int)(Math.pow(2,i) * lastDigit) + binToDec(bin/10, ++i); } } |

**Output**

`Enter a Binary`

1111

Decimal: 15

If you have any doubts or suggestions then below.