Decimal to binary conversion using Java

Decimal to binary conversion using java :

 
In this article we will create a java program for converting a decimal number to its binary form. For this purpose we need to ask a decimal number from user and convert that decimal number to its binary equivalent form and then print the converted number on to the screen.
 
For conversion, we divide the decimal number by 2 and get the quotient for the next iteration and continuously store the remainder value in an array in reverse order till the decimal number is greater than 0. For better understanding with an example just have a look towards the diagram shown at the right.
Decimal to binary conversion using Java

Working :

Step 1 : Ask the user to enter a decimal number.

Step 2 : Declare an array and a variable for pointing index value of the array.

Step 3 : Use  the while loop till decimal number entered by user is greater than 0.

Step 4 : Divide the decimal number by 2 and store the remainder in the array and update the decimal number with the quotient.

Step 5 : Repeat the steps 3 and 4 till the decimal number is greater than 0.

Step 6 : Print the array in reverse order.

Code in Java :

//Java program to convert decimal number to binary number
import java.util.Scanner;
public class Decimal_To_Binary
{
public static void main(String args[])
{
//scanner class object creation
Scanner sc = new Scanner(System.in);
//input from user
System.out.print("Enter a Decimal number : ");
int decimal = sc.nextInt();
//integer array for storing binary digits
int binary[] = new int[20];
int i = 0;
//writing logic for the conversion
while(decimal > 0)
{
int r = decimal % 2;
binary[i++] = r;
decimal = decimal/2;
}
//printing result
System.out.print("Binary number : ");
for(int j = i-1 ; j >= 0 ; j--)
System.out.print(binary[j]+" ");
//closing scanner class(not compulsory, but good practice)
sc.close();
}
}

Output :

Enter a Decimal number : 26
Binary number : 1 1 0 1 0