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.
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.
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));}}
In the code above:
int variable val with the value 12.int val = 12;
toBinaryString method to convert the int value to binary representation.Integer.toBinaryString(val)
bitCount method with val as the argument. We will get 2 as a result.Integer.bitCount(val);