# Java Program-How To Count The Number Of Bits?

0
1008 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.

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.``````
``````Ex.2: Input n=21
Output the no of bits 3
The binary representation of 21 is 10101 and has 3 set bits
.
``````

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) {
count++;
}
n = n / 2;
}
return count;
}

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

```

Output:

``````Enter the number
:7
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. 