Java Program to Convert Decimal to Binary using Recursion

In this tutorial, we will write a program to convert a decimal number into binary in java using recursion. Before that, you must have knowledge of the following topics in java.

Binary number

The binary numbers are based on 0 and 1, so it is a base 2 number. They are the combination of 0 and 1. For example, 1001, 110101, etc.

Decimal Number

These are the numbers with a base of 10, which ranges from 0 to 9. These numbers are formed by the combination of 0 to 9 digits such as 24, 345, etc.

Here is the chart where for the equivalent value of decimal and binary numbers.

Decimal to binary

Example:

Input: 5
Output: 101

Input: 7
Output: 111

Now let us go through a program for the conversion of decimal to binary in java using recursive function.


Java Program to Convert Decimal to Binary using Recursion

Source code:

import java.io.*;
import java.util.Scanner;

public class Main
{
   public static void main(String args[])
   {
      int dec;
      Scanner in = new Scanner(System.in);

      System.out.println("Enter a decimal number: ");
      dec = in .nextInt();

      System.out.print("Equivalent Binary Value: ");
      System.out.println(conversionFunc(dec));	//calling recursive function

   }

   //recursive function
   public static int conversionFunc(int decNumber)
   {
      if (decNumber == 0)
         return 0;
      else
         return (decNumber % 2 + 10* conversionFunc(decNumber / 2));
   }
}

Output:

Enter a decimal number:
7
Equivalent Binary Value: 111