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 for decimal to binary conversion is the most common java interview question.

Also read – java decimal to binary using toBinaryString and stack

In this 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.

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("Binary number : " + strConvert);
System.out.println("Number of 1s : " + count);
sc.close();
}
}

Output:

Enter a decimal number : 266
Binary number : 0 1 0 1 0 0 0 0 1
Number of 1s : 3

Also read – decimal to binary java logic