# Java program to count set bits in an Integer

In this tutorial, we will discuss the logic behind counting the number of set bits in Java. Also, we will implement a Java program that will count the number of set bits.

**What are Set Bits?**

The Binary representation of a number is done in the form of zero’s and one’s. The number of one’s that are present in the equivalent binary representation of an integer are called as **Set Bits.**

For demonstration purpose let us consider the below example:

Decimal number: **17**

Binary representation of 17:

1 |
0 |
0 |
0 |
1 |

Number of set bits: **2**

Explanation: In the above binary number representation of 17, the count of number of one’s

in the binary number is 2. Hence, the number of set bits are 2.

### Java program to count set bits in an Integer

import java.io.*; public class main { static int bits_counter(int number) { int count = 0; while (number > 0) { count += number & 1; number >>= 1; } return count; } public static void main(String args[]) { int number = 17; System.out.println(bits_counter(number)); } }

**Output : 2
**

**Explanation**: In the above program I have written the logic for computing the number of set bits in simplistic manner. Beginning from the void main() function, the decimal number is declared as 17. The number of set bits of number 17 will be computed. The number is passed to the function bits_counter() as parameter, the function computes the number of set bits in the number and returns the result to the main function. The operator ‘>>’ used in the bits_counter() function uses the sign bit (left most bit) to fill the trailing positions after the shift. Henceforth, the count is stored in the count variable, and when the while loop condition for number greater than 0 is satisfied, the count is returned.

Time Complexity: O(1)

Space Complexity: O(1)

## Leave a Reply