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 objectBitSet bitSet = new BitSet();// Set the bit at index 2bitSet.set(2);// Set the bit at index 8bitSet.set(8);int startingIndex = 4;// get the first bit set to false from the startingIndexSystem.out.printf("%s.nextClearBit(%s) = %s", bitSet, startingIndex, bitSet.nextClearBit(startingIndex));}}
Explanation
- In line 1, we import the
BitSetclass. - In line 7, we create an object of the
BitSetclass. - In lines 10 and 13, we set the bits at indexes 2 and 8 of the
BitSetobject. - In line 15, we define the starting index for the
nextClearBitmethod. - In line 18, we get the first bit set to
falsefrom thestartingIndexusing thenextClearBitmethod.