Java Program to Convert Decimal to Binary using Recursion

This is a Java Program to Convert a Number Decimal System to Binary System using Recursion.

Enter any number as an input. Now we make a new method named binary with return type string that gives us the desired result with the help of modulus operation.

Here is the source code of the Java Program to Convert a Number Decimal System to Binary System using Recursion. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.

  1. import java.util.Scanner;
  2. public class Convert
  3. {
  4.     public static void main(String[] args) 
  5.     {
  6.         int n;
  7.         String x;
  8.         Scanner s = new Scanner(System.in);
  9.         System.out.print("Enter any decimal number:");
  10.         n = s.nextInt();
  11.         Convert obj = new Convert();
  12.         x = obj.binary(n);
  13.         System.out.println("Binary number:"+x);
  14.     }
  15.     String binary(int y)
  16.     {
  17.         int a;
  18.         if(y > 0)
  19.         {
  20.             a = y % 2;
  21.             return (binary(y / 2) + "" +a);
  22.         }
  23.         return "";
  24.     }
  25. }

Output:

$ javac Convert.java
$ java Convert
 
Enter any decimal number:25
Binary number:11001

Sanfoundry Global Education & Learning Series – 1000 Java Programs.

advertisement
advertisement

Here’s the list of Best Books in Java Programming, Data Structures and Algorithms.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.