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
intvariablevalwith the value12.
int val = 12;
- In line 5, we use the
toBinaryStringmethod to convert theintvalue to binary representation.
Integer.toBinaryString(val)
- In line 6, we call the
bitCountmethod withvalas the argument. We will get2as a result.
Integer.bitCount(val);