What is the Integer.bitCount method in Java?

The bitCount static method of the Integer class can be used to find the number of 1 bits in the two’s complement binary representation of the given int value.

Syntax

public static int bitCount(int val)

The bitCount method takes the int value as an argument and returns an integer value that represents the number of 1s present in the two’s complement binary representation of the argument.

Code

The example below demonstrates how to use the bitCount method.

class IntegerBitCountExample {
public static void main( String args[] ) {
int val = 12;
System.out.println("The Integer value is :" + val);
System.out.println("Binary representation of " + val + " is:" +Integer.toBinaryString(val));
System.out.println("Number of 1s is: " + Integer.bitCount(val));
}
}

Explanation

In the code above:

  • In line 3, we create a int variable val with the value 12.
int val = 12;
  • In line 5, we use the toBinaryString method to convert the int value to binary representation.
Integer.toBinaryString(val)
  • In line 6, we call the bitCount method with val as the argument. We will get 2 as a result.
Integer.bitCount(val);

Free Resources