This is a Java Program to Convert a Decimal Number to Binary & Count the Number of 1s.

Enter any integer as an input. Now we convert the given decimal input into a binary number with the help of division and modulus operations along with loops and if conditions to get the desired output.

Here is the source code of the Java Program to Convert a Decimal Number to Binary & Count the Number of 1s. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.

import java.util.Scanner;

public class Convert

`{`

public static void main(String[] args)

`{`

int n, count = 0, a;

String x = "";

Scanner s = new Scanner(System.in);

System.out.print("Enter any decimal number:");

n = s.nextInt();

while(n > 0)

`{`

a = n % 2;

if(a == 1)

`{`

`count++;`

`}`

x = x + "" + a;

n = n / 2;

`}`

System.out.println("Binary number:"+x);

System.out.println("No. of 1s:"+count);

`}`

`}`

Output:

$ javac Convert.java $ java Convert Enter any decimal number:25 Binary number:10011 No. of 1s:3

**Sanfoundry Global Education & Learning Series – 1000 Java Programs.**

Here’s the list of Best Reference Books in Java Programming, Data Structures and Algorithms.