Java BitSet cardinality() method

The cardinality() method of Java BitSet class returns the number of bits set which are true in this BitSet.

Syntax:

Parameter:

NA

Returns:

The cardinality() method returns the number of bits set which are true in this BitSet.

Exception:

NA

Compatibility Version:

Java 1.4 and above

Example 1

Output:

bitset: {0, 1, 2, 5, 6}
number of true bits: 5
bitset after clear index 2: {0, 1, 5, 6}
number of true bits after clear index 2: 4

Example 2

In this example, we are creating a BitSet object using string of bits as input and applying cardinality() method on it.

Output:

bitset: {0, 2, 4}
number of true bits: 3