Decimal To Binary Conversion Java Program

By |2018-12-08T14:05:05+05:30June 18th, 2016|java programs|

Here we are going to write a program on conversion of Decimal To Binary Numbers in Java.

Decimal To Binary conversion in Java :

ConvertDecimalToBinary.java
import java.util.Scanner;

public class ConvertDecimalToBinary {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter any Decimal Number : ");
        int input = sc.nextInt();
        System.out.println("Binary is : " + convertDecimalToBinary(input));
    }

    public static String convertDecimalToBinary(int decimal) {
        String binary = "";
        if (decimal != 0) {
            while (decimal > 0) {
                binary = decimal % 2 + binary;
                decimal /= 2;
            }
        }
        return binary;
    }
}

Output:

Enter any Decimal Number : 150
Binary is : 10010110

Decimal To Binary Recursion :

DecimalToBinary.java
import java.util.Scanner;

public class DecimalToBinary {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter any Decimal Number : ");
        int input = sc.nextInt();
        binaryRepresentation​​(input);
    }

    public static void binaryRepresentation​​(int n) {
        if(n==0) {
            return;
        }
        binaryRepresentation​​(n/2);
        System.out.print(n%2);
    }
}

Output:

Terminal
Enter any Decimal Number : 100
1100100

Happy Learning 🙂

About the Author:

Hi Folks, you have reach this so far, that shows you like what you are learning. Then why don't you support us to improve for bettor tutorials by leaving your valuable comments and why not you keep in touch with us for latest updates on your favorite blog @ facebook , twitter , Or Google+ ,

Leave A Comment