Decimal to binary java

Hey guys!! Welcome to flower brackets blog. Today in this post we will learn decimal to binary java.

Here in this java program user will be asked to enter decimal number to convert it into binary and display it. In the previous post we learnt how to convert binary number to decimal number.

In the below example we will be using Scanner class of java.util package. I’m going to show you how exactly decimal number 20 is converted to binary. So you have the number 20 divide that by 2 you get quotient 10 and remainder 0.

Now at this point we get one binary digit, that is 0, at the end as the remainder. Remember the remainder is what gives you the binary digit. Now take the quotient separately again divide that by 2 and you get the quotient as 5 and remainder as 0.

Again take quotient 5 repeat the same thing. 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.

In the last step take the quotient as 1 and as you can see the remainder is going to be 1. Now, collecting all the remainders, you get 00101. Actually this is not the binary number.

We have to take the reverse, that is, 10100(we have to read it from right to left). Finally here’s the java program,

decimal to binary java

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; 
      // here we are printing binary in reverse order 
      for(int a = count - 1; a >= 0; a--) 
   public static void main(String[] args)
      int number = 20; 



Also read – decimal to binary using toBinaryString and stack

Related Posts