# BitSet int nextSetBit(int fromIndex) Method Example Program

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.
To iterate over the true bits in a BitSet, use the following loop:

for (int i = bs.nextSetBit(0); i >= 0; i = bs.nextSetBit(i+1)) {
// operate on index i here
}

#### Program

```package com.candidjava;

import java.util.BitSet;

/**
* @author : vinod kumar v
* @description :The BitSet.nextSetBit(int fromIndex) method returns the index
*              of the first bit that is set to true that occurs on or after the
*              specified starting index.
* */

public final class BitSetNextSet {
public static void main(String[] args) {

BitSet obj = new BitSet(8);
BitSet obj1 = new BitSet(8);

obj.set(0);
obj.set(1);
obj.set(2);
obj.set(3);

obj1.set(2);
obj1.set(4);
obj1.set(6);
obj1.set(8);

System.out.println("The Value in obj:" + obj);
System.out.println("The Value in obj1" + obj1);

System.out.println(" the nextset bit is:" + obj.nextSetBit(0));
System.out.println("the nextset bit is:" + obj1.nextSetBit(6));
}
}
```

#### Output

The Value in obj:{0, 1, 2, 3}
The Value in obj1{2, 4, 6, 8}
the nextset bit is:0
the nextset bit is:6

#### Explanation

public int nextSetBit(int fromIndex)
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.
To iterate over the true bits in a BitSet, use the following loop:

for (int i = bs.nextSetBit(0); i >= 0; i = bs.nextSetBit(i+1)) {
// operate on index i here
}
Parameters:
fromIndex - the index to start checking from (inclusive)
Returns:
the index of the next set bit, or -1 if there is no such bit
Throws:
IndexOutOfBoundsException - if the specified index is negative

Related Post