Java BitSet nextSetBit() method

The nextSetBit(int fromIndex) method of Java BitSet class returns the index of the first bit which is set to true that occurs on or after the specified index. If the BitSet does not contain any set bit then it returns -1.

Syntax:

Parameter:

DataTypeParameterDescription
intfromIndexIt is an index of BitSet from which the checking of set bit starts.

Returns:

The nextSetBit(int fromIndex) method returns the index of next set bit or -1 if no bi is set to true.

Exception:

IndexOutOfBoundsException - throw an exception if the specified index is negative.

Compatibility Version:

Java 1.4 and above

Example 1

Output:

set bit next or on to 0: 0
set bit next or on to 2: 4

Example 2

The nextSetBit(int fromIndex) method throws an exception if the specified index is negative.

Output:

bitset: {0, 1, 4, 5, 7}
Exception in thread "main" java.lang.IndexOutOfBoundsException: fromIndex < 0: -1
	at java.util.BitSet.nextSetBit(Unknown Source)
	at BitSetNextSetBitExample2.main(BitSetNextSetBitExample2.java:15)

Example 3

The nextSetBit(int fromIndex) method returns -1 if no set bit found in the BitSet.

Output:

bitset: {}
set bit on or next to 0: -1