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

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

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

Java program to convert decimal to binary is the most common java interview question.

Also read – decimal to binary in java inbuilt function

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

In java program to convert decimal to binary first user enters an integer number as an input using nextInt() method of scanner class.

Also read – java program to convert decimal to binary using recursion

This user input is stored in integer variable ‘number’. Then to convert from decimal to binary we use division operator and modulus operator along with “while” loop and “if” statement to get the output.

Also read – java program to convert decimal to binary using for loop

Here’s the java program to convert decimal to binary using while loop.

// 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.println("Enter a decimal number : ");
      number = sc.nextInt();
      // decimal to binary java
      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 – java program to convert binary to decimal

Also read – java program to convert decimal to binary and vice versa

Also read – function to convert decimal to binary in java

Also read – java program to convert decimal to octal