What is BitSet.nextClearBit() in Java?

Overview

nextClearBit() is an instance method of the BitSet which is used to get the index of the first bit that is set to false on or after the given beginning index.

The nextClearBit() method is defined in the BitSet class. The BitSet class is defined in the java.util package. To import the BitSet class, check the following import statement.

import java.util.BitSet;

Syntax

The syntax of nextClearBit() is as follows:


public int nextClearBit(int fromIndex)

Parameters

  • int fromIndex: The starting index.

Return value

This method returns the index of the next clear bit.

Code

Let’s look at a working example of the nextClearBit() method:

import java.util.BitSet;
public class Main{
public static void main(String[] args) {
// Create empty BitSet object
BitSet bitSet = new BitSet();
// Set the bit at index 2
bitSet.set(2);
// Set the bit at index 8
bitSet.set(8);
int startingIndex = 4;
// get the first bit set to false from the startingIndex
System.out.printf("%s.nextClearBit(%s) = %s", bitSet, startingIndex, bitSet.nextClearBit(startingIndex));
}
}

Explanation

  • In line 1, we import the BitSet class.
  • In line 7, we create an object of the BitSet class.
  • In lines 10 and 13, we set the bits at indexes 2 and 8 of the BitSet object.
  • In line 15, we define the starting index for the nextClearBit method.
  • In line 18, we get the first bit set to false from the startingIndex using the nextClearBit method.

Free Resources