Java Exercises: Accept an integer and convert it into a binary representation

Java Basic: Exercise-163 with Solution

Write a Java program that will accept an integer and convert it into a binary representation. Now count the number of bits which is equal to zero of the said binary representation.

Pictorial Presentation:

Java Basic Exercises: Accept an interger and convert it into a binary representation.

Sample Solution:

Java Code:

import java.util.Scanner;
public class Solution {	
	public static int countBitsTozeroBasedOnString(int n) {
    int ctr = 0;
    String binaryNumber = Integer.toBinaryString(n);
	System.out.print("Binary representation of "+n+" is: "+binaryNumber);
    for (char ch : binaryNumber.toCharArray()) {
      ctr += ch == '0' ? 1 : 0;
    return ctr;
    public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
        System.out.print("Input first number: ");
        int n = in.nextInt();
		System.out.println("\nNumber of zero bits: " + countBitsTozeroBasedOnString(n));

Sample Output:

Input first number:  25
Binary representation of 25 is: 11001
Number of zero bits: 2s


Flowchart: Java exercises: Accept an interger and convert it into a binary representation.

Java Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a Java program to find the numbers greater than the average of the numbers of a given array.
Next: Write a Java program to divide the two given integers using subtraction operator.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

Follow us on Facebook and Twitter for latest update.

Java: Tips of the Day

Java: Anagrams

Generates all anagrams of a string.

public static List<String> anagrams(String input) {
    if (input.length() <= 2) {
        return input.length() == 2
                ? Arrays.asList(input, input.substring(1) + input.substring(0, 1))
                : Collections.singletonList(input);
    return IntStream.range(0, input.length())
            .mapToObj(i -> new SimpleEntry<>(i, input.substring(i, i + 1)))
            .flatMap(entry ->
                    anagrams(input.substring(0, entry.getKey()) + input.substring(entry.getKey() + 1))
                            .map(s -> entry.getValue() + s))

Ref: https://bit.ly/3rvAdAK