Decimal to binary conversion using Java

Decimal to Binary conversion using Java

In this article we will create program for decimal to binary conversion using java. 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.
Example : Decimal number 5 = 101 in binary representation.
Decimal to binary

Working :

Step 1 : Ask the user to enter a decimal number and store it in variable say decimal.

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 i.e, (decimal>0).

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

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

Step 6 : Print the array in reverse order, as it represents the binary representation of the given decimal number.

Decimal to binary conversion using java

Code for Decimal to binary conversion using 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