Java.lang Package Classes

Java Integer - bitCount() Method



The java.lang.Integer.bitCount() method returns the number of one-bits in the two's complement binary representation of the specified int value. This function is sometimes referred to as the population count.

Syntax

public static int bitCount(int i)

Parameters

i Specify the value whose bits are to be counted.

Return Value

Returns the number of one-bits in the two's complement binary representation of the specified int value.

Exception

NA.

Example:

In the example below, the java.lang.Integer.bitCount() method returns the number of one-bits in the two's complement binary representation of the given int value.

import java.lang.*;

public class MyClass {
  public static void main(String[] args) {
    
    //creating int value
    int x = 135;

    //printing x
    System.out.println("The x is = " + x);     

    //printing the binary representation of x
    System.out.println("The x in binary is = " + Integer.toBinaryString(x)); 

    //printing the number of one-bits in x
    System.out.println("Number of one bits in x = " + Integer.bitCount(x)); 
  }
}

The output of the above code will be:

The x is = 135
The x in binary is = 10000111
Number of one bits in x = 4

❮ Java.lang - Integer