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 = a + "" + x;

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:11001 No. of 1s:3

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

advertisement

advertisement

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

**If you find any mistake above, kindly email to [email protected]**

**Related Posts:**

- Apply for Java Internship
- Practice Programming MCQs
- Apply for Computer Science Internship
- Check Programming Books
- Check Java Books