Java Utility Library

Java BitSet - nextSetBit() Method



The java.util.BitSet.nextSetBit() method returns the index of the first bit that is set to true that occurs on or after the specified starting index. If no such bit exists then -1 is returned.

Syntax

public int nextSetBit(int fromIndex)

Parameters

fromIndex Specify the index to start checking from (inclusive).

Return Value

Returns the index of the next set bit, or -1 if there is no such bit.

Exception

Throws IndexOutOfBoundsException, if the specified index is negative.

Example:

In the example below, the java.util.BitSet.nextSetBit() method returns the index of the first bit which is set to true and occurs on or after the specified starting index in the given BitSet.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating a BitSet
    BitSet BSet = new BitSet();

    //populating BitSet
    BSet.set(1);
    BSet.set(2);
    BSet.set(3);
    BSet.set(10);
    BSet.set(11); 

    //printing BitSet
    System.out.println("BSet contains: " + BSet);

    //finding index of the bit which is set to true
    //which occurs on or after index = 5
    System.out.print("bit which is set to true on or after index 5 is: ");
    System.out.print(BSet.nextSetBit(5));
  }
}

The output of the above code will be:

BSet contains: {1, 2, 3, 10, 11}
bit which is set to true on or after index 5 is: 10

❮ Java.util - BitSet