Java Program-How To Count The Number Of Bits?

croe java topics

In this article, you get a Solution for How to count the number of bit in Java. and also learn about what is bit and how we can count the number of bits

What are Bits and Bytes in java?

Every Information is stored as bits and bytes in the storage memory of the computer. because bits and bytes are the smallest blocks of memory storage. after this paragraph, you can read the basic information about bits and bytes.

1Bits short form is BINARY Digitsone byte is contains 8 bits
2it is a smallest unit of memory storageit’s look like: 01010110
3it is stored in the form of 0 and 1.1 byte can store one character like A, x, $
4in the computer memory all files are saved in 0’s and 1’s
5Group of 8 bits will be make a 1 byte.

Here is a Example for better understanding:

Ex.1: Input: n=3
Output: the no of bits 2
The binary representation of 3 is 11 and has 2 set bits.
The binary representation of 2 set bits, example of bits set
Ex.2: Input n=21
Output the no of bits 3
The binary representation of 21 is 10101 and has 3 set bits
The binary representation of 3 set bits, example of bits set

Here is the source code (.javaFile) of the Java Program to Count the Number of Bits. This Java program compiled in the Windows system.

How to Count the Number of Bit in Java?

import java.util.Scanner;

public class SetedNo {
	static int countbits(int n) {
		int count = 0;
		while (n > 0) {
			if (n % 2 == 1) {
			n = n / 2;
		return count;

	public static void main(String[] args) {
		Scanner sc = new Scanner(;
		System.out.println("Enter the no");
		int n = sc.nextInt();
		int s = countbits(n);
		System.out.println("the no of bits " + s);


Enter the number
the no of bits 3

Code Explanation:-

  1. Creating a class “SetedNo”
  2. Create a static method “countbits”
  3. Take a variable “count”
  4. Using while loop
  5. Apply the main method
  6. Import Scanner class
  7. Input from the user
  8. Read the user enter number
  9. Assign the values of method returns in a variable
  10. Print the final result with println method.

Admin words:- here we are cover some information about bits and bytes. hopefully, now you can understand the program. how to calculate the number of bit in java. if still you have any confusion please feel free to ask in the comment section.

0 0 votes
Article Rating
croe java topics

Previous articleJVM Architecture | How JVM Works? | JVM in Java Full Explained
Next articleHappy Number in Java? | How to check Number is Happy or UnHappy?
Notify of
Inline Feedbacks
View all comments