Convert Decimal to Binary in Java

Here you will get program to convert decimal to binary in Java.

Below I have shared 3 different methods for java decimal to binary conversion.

Also Read: Convert Binary to Decimal in Java

Convert Decimal to Binary in Java

Convert Decimal to Binary in Java

1. Integer.toString() Method

We can convert a decimal number to binary using toString() method of Integer class. This method takes two arguments, first argument is the decimal number and second is the base in which we want to convert. For binary the base is 2.

Output

Enter a decimal number:
8
Binary number is 1000

2. Integer.toBinaryString()

It is another method of Integer class that can directly convert decimal to binary. See below program to know how to use it.

Output

Enter a decimal number:
10
Binary number is 1010

3. Own Logic

We can write our own logic for decimal to binary conversion in java. It can be done by following steps.

  1. Divide the number by 2 using % operator and store the remainder somewhere.
  2. Divide the number by 2 using / operator.
  3. Repeat above two steps until number becomes 0.
  4. Now print the remainders in reverse order.

Below program implements this simple algorithm.

Output

Enter a decimal number:
2
Binary number is 10

Comment below if you have doubts or know any other way to convert decimal to binary in Java.

Leave a Reply

Your email address will not be published. Required fields are marked *