Now in this post we will learn convert decimal to binary java example.

Here user will be asked to enter decimal number to convert it into decimal number and display it.

In the previous post we learnt how to convert binary number to decimal number java example.

In the below example we will be using Scanner class of java.util package.

For example, decimal number 20 –

I’m going to show you how exactly decimal number 20 is converted 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).

#### Example: Convert Decimal to Binary Java Example

import java.util.Scanner; public class Decimal_To_Binary { public String to_Binary(int a){ if(a == 0){ return "0"; } String binary = ""; while(a > 0){ int deci = a % 2; binary = deci + binary; a = a / 2; } return binary; } public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Please enter number to convert: "); int decimal = sc.nextInt(); Decimal_To_Binary cdtb = new Decimal_To_Binary(); String pro = dtb.to_Binary(decimal); System.out.println("Converted binary value is " + pro); } }

**Output:**