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

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

advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification 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
I’m Manish - Founder and CTO at Sanfoundry. I’ve been working in tech for over 25 years, with deep focus on Linux kernel, SAN technologies, Advanced C, Full Stack and Scalable website designs.

You can connect with me on LinkedIn, watch my Youtube Masterclasses, or join my Telegram tech discussions.

If you’re in your 20s–40s and exploring new directions in your career, I also offer mentoring. Learn more here.