Convert Decimal To Binary in Java


The convert decimal to binary is by dividing the given decimal number recursively by 2. Then, the remainders are noted down till we get 0 as the final quotient. After this step, these remainders are written in reverse order to get the binary value of the given decimal number.

Source Code

import java.util.Scanner;
 
public class decimal_binary {
    public static void decimal2Binary(int n)
    {
        int[] binaryNum = new int[1000];
 
        int i = 0;
        while (n > 0)
        {
            binaryNum[i] = n % 2;
            n = n / 2;
            i++;
        }
        for (int j = i - 1; j >= 0; j--)
            System.out.print(binaryNum[j]);
    }
    public static void main(String args[]) {
        Scanner in =new Scanner(System.in);
        System.out.println("Enter The Decimal No : ");
        int n = in.nextInt();
        System.out.println("Decimal No : " + n);
        System.out.print("Binary No : ");
        decimal2Binary(n);
    }
}
 

Output

Enter The Decimal No :
10
Decimal No : 10
Binary No : 1010
To download raw file Click Here

Basic Programs