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 🙂

Leave A Comment