Integer.bitCount() method in Java

In Java, the bitCount() method is a static method of the Integer wrapper class. It returns the total number of one bit in two’s complement binary representation of the given integer value. However, if the value is a character, it will return the number of one bit in the binary equivalent of the ASCII value of that character.

Method signature:

The signature for the bitCount() method is as shown below. As, this is a static method, this is called with a class name.

Integer.bitCount(i)

Method parameters and return type:

  • Here, the bitCount() method takes an integer as a parameter.
  • However, it returns an int value as a count.

Java Integer bitCount Examples:

Example 1:In this example, we are initializing the int variable with a positive value. Thereafter, we are counting the number of one bit in its binary equivalent.

public class Main
{
    public static void main(String[] args) {
       // Initializing 
       int i=7;
	   
       // Printing the bit count along with binary equivalent of the int value
       System.out.println("Binary Equivalent of 7 is 0111. So, bit count is "+Integer.bitCount(i));
    }
}

Output

Binary Equivalent of 7 is 0111. So, bit count is 3

Example:

In this example, we are initializing the int variable with a negative value. Thereafter, we are counting the number of one bit in its binary equivalent.

public class Main
{
    public static void main(String[] args) 
	{
		// Initializing with negative value
		int i=-7;
	   
	   	// Printing the bit count along with binary equivalent of the int value
       System.out.println("Binary Equivalent of "+i+" is "+Integer.toBinaryString(i)+" So, bit count is "+Integer.bitCount(i));
    }
}

Output

Binary Equivalent of -7 is 11111111111111111111111111111001 So, bit count is 30

Example:

In this case, we are initializing the int variable with a char value. So, its ASCII value is stored in the int variable. Thereafter, we are counting the number of one bit in its binary equivalent.

public class Main
{
    public static void main(String[] args) 
	{
		// Initializing int variable with char value
		int i='A';
		
		// Printing the bit count along with binary equivalent of the int value
       System.out.println("Binary Equivalent of "+i+" is "+Integer.toBinaryString(i)+" So, bit count is "+Integer.bitCount(i));
    }
}

Output

Binary Equivalent of 65 is 1000001 So, bit count is 2

Conclusion

Hence, the bitCount() method returns the total number of one bit in a binary equivalent of the given number.

References

Happy Learning 🙂