# Convert Binary to Decimal using Recursion

Write a program in Java to accept a binary number and convert it into its decimal equivalent using recursive function. Display a suitable message if the binary number is negative and if it does not contain 1s and 0s.

Example:
Sample Input:
Enter a binary number: 110011
Sample Output:
The decimal equivalent: 51

``````import java.io.*;
class BinaryToDecimal{
public static void main(String args[])throws IOException{
System.out.print("Binary integer: ");
if(!valid(bin)){
System.out.println("Invalid Binary Number!");
return;
}
int d = convert(bin, 0);
System.out.println("Decimal equivalent = " + d);
}
public static boolean valid(int bin){
String b = Integer.toString(bin);
if(b.length() == 0)
return false;
for(int i = 0; i < b.length(); i++){
if(b.charAt(i) != '1' && b.charAt(i) != '0')
return false;
}
return true;
}
public static int convert(int b, int p){
if(b == 0)
return 0;
if(b == 1)
return (int)Math.pow(2, p);
return b % 10 * (int)Math.pow(2, p) + convert(b / 10, p + 1);
}
}``````

### 5 thoughts on “Convert Binary to Decimal using Recursion”

1. Sir,a program is given which states that:
WAP in JAVA to create a matrix of size 7 X 6 in such a way that the numbers 1 to 5 are kept in the matrix in normal and reverse manner in cyclic fashion i.e 1 to 5 then 5 to 1 .

• Please clarify this with an example. Then I might help.

• Eg:
1234554
321…….
And so on

2. • 