Write a Java Program to Convert a decimal number into its binary representation.

**Example:**

1 2 3 4 5 | Input: 5 Output: 101 Input: 2 Output: 10 |

The method is very simple. We need to **divide the decimal number by 2 until it reduces to 0**. The **remainders which we will get in reverse order will give the binary representation** of the corresponding decimal number.

To achieve the remainder in the bottom-up manner we need to concatenate each of the upcoming remainders to the left of the concatenated binary number. For this, we will need to first **multiply equal number 10 to the remainder** as the number of digits already present in the concatenated binary number and then add to the concatenated binary number.

Let’s implement the same in Java.

## Convert Decimal to Binary in Java using While Loop

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner in= new Scanner(System.in); System.out.println("Enter a number"); int num = in.nextInt(); int i=1, binary=0; while(num!=0){ binary += i*(num%2); num = num/2; i=i*10; } System.out.println("Binary: "+ binary); } } |

**Output**

`Enter a number`

5

Binary: 101

## Convert Decimal to Binary in Java using Recursion

In this method we will pass the quotient to each recursive call until it reduces to zero, then will start outputting the remainder from the last.

Since recursion implements stack, so the output of the remainder will happen from the last recursive call.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner in= new Scanner(System.in); System.out.println("Enter a number"); int num = in.nextInt(); System.out.print("Binary: "); decToBin(num); } private static void decToBin(int n){ if(n > 0){ //recall by passing quotient decToBin(n/2); //print remainder System.out.print(n%2); } } } |

**Output**

`Enter a number`

15

Binary: 1111

Comment below your suggestion or doubts if you have any.