java.lang.Integer bitCount(int i)

Description :

This java tutorial shows how to use the bitCount() method of Integer class under java.lang package. This method return an int which correspond to the count of the one’s bits of the 2’s complement of the int method argument.

Method Syntax :

public static int bitCount(int i)

Parameter Input :

DataType Parameter Description
int i the value which want to get how many one's bits it's 2's complement.

Method Returns :

The toOctalString(int i) method simply returns the number of one-bits in the two’s complement binary representation of the specified int value.

Compatibility Version :

Requires Java 1.5 and up

Exception :

N/A

Discussion :

The bitCount() method is static thus we should invoke it statically for example Integer.bitCount(int i). This method simply converts the int parameter into binary string and then returns the number of one’s bits.

Java Code Example :

This java example source code demonstrates the use of bitCount() method of Integer class. Basically we shows the equivalent binary string of the int value provided as method argument and we print how many one’s bit does the binary string have.

package com.javatutorialhq.java.examples;
import static java.lang.System.*;

/*
 * This example source code demonstrates 
 * the use of bitCount method of Integer class
 */
 
 public class IntegerBitCount {

 public static void main(String[] args) {
 int value = 178;
 // Get the binary equivalent
 out.println("Binary equivalent:"+Integer.toBinaryString(value));
 // get the  number of one's
 out.println("Bit Count:"+Integer.bitCount(value));

 }
 
 }

Sample Output :

Running the bitCount(int i) method example source code of Integer class will give you the following output

Binary equivalent:10110010
 Bit Count:4

Exception Scenario :

N/A

Similar Method :

  • N/A

Suggested Reading List :

References :