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 DecimalToBinary { public String toBinary(int a) { if(a == 0) { return "0"; } String strBinary = ""; while(a > 0) { int b = a % 2; strBinary = b + strBinary; a = a / 2; } return strBinary; } public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Please enter number to convert: "); int decimal = sc.nextInt(); DecimalToBinary dtb = new DecimalToBinary(); String str = dtb.toBinary(decimal); System.out.println("Converted binary value is " + str); } }

**Output:**

##### conclusion

So this is all about how to convert decimal to binary in java with an explanation and example.

I hope you guys have understood the concept about java program to convert decimal to binary.

You can subscribe to my blog flower brackets, if you haven’t already.

Do share this article if you like.