Let’s learn java program to convert decimal number to binary.
Java program to convert decimal number to binary
In this post I’m going to show you program to convert decimal number to binary number without using predefined method.
As you can see below image given number is 20 divide that by 2 to get quotient 10 and remainder 0. Now at this point we get one binary digit, that is 0 as the remainder.

Remember the remainder is what gives you the binary digit. Now take quotient 10 again divide that by 2 and you get the quotient as 5 and remainder as 0.
Again take quotient 5. Divide that by 2 you will get the quotient as 2 and remainder as 1. Repeat the same procedure divide that by 2, you will get quotient as 1 and remainder as 0.
Now in the last step quotient is 1 and remainder is 1. Now, collecting all the remainders, you get 00101. Actually this is not the binary number.
We have to read it reverse direction, that is, 10100 (we have to read it from right to left). Now let’s see program to convert decimal number to binary.
public class DecimalToBinaryDemo { // this function converts decimal to binary static void toBinary(int num) { // here we are storing binary number int binaryNumber[] = new int[1000]; // "count" variable is counter for binary array int count = 0; while(num > 0) { // storing remainder in binary array binaryNumber[count] = num % 2; num = num / 2; count++; } // here we are printing binary in reverse order for(int a = count - 1; a >= 0; a--) System.out.print(binaryNumber[a]); } public static void main(String[] args) { int number = 20; toBinary(number); } }
Output:
10100
Also read – classes and objects in java