Java program to convert decimal number to binary & count number of 1s

Let’s learn (decimal to binary java) java program to convert decimal number to binary & count number of 1s.

Java program to convert decimal number to binary & count number of 1s

Convert a number to binary java is the most common java interview question.

In convert to binary java program first user enters an integer number as an input. Then to convert from decimal to binary we use division and modulus operation along with “while” loop and “if” condition to get the output.

Here’s the decimal to binary java code,

```// decimal to binary conversion in java
import java.util.Scanner;
```
```public class DecimalBinaryDemo
{
public static void main(String[] args)
{
int number, count = 0, temp;
String strConvert = "";
Scanner sc = new Scanner(System.in);
System.out.print("Enter a decimal number : ");
number = sc.nextInt();
while(number > 0)
{
temp = number % 2;
if(temp == 1)
{
count++;
}
strConvert = strConvert + " " + temp;
number = number / 2;
}
System.out.println("Decimal to binary in java : " + strConvert);
System.out.println("Number of 1s : " + count);
sc.close();
}
}

```

Output:

Enter a decimal number : 266
Decimal to binary in java : 0 1 0 1 0 0 0 0 1
Number of 1s : 3

Also read – decimal to binary java logic