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

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

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

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();
      // 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 – selection sort java