Java BitSet previousSetBit() method

The previousSetBit(int fromIndex) method of Java BitSet class returns the index of the nearest bit which is set to true that occurs on or before the specified index. It returns -1 if the specified index is negative or no such set bit exists in the BitSet.

Syntax:

Parameter:

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

Returns:

This method returns the index of the previous set bit, or -1 if there is no such set bit exists.

Exception:

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

Compatibility Version:

Java 1.7 and above

Example 1

Output:

bitset: {0, 1, 4, 6, 7}
previous set bit on or before 4: 4
previous set bit on or before 5: 4

Example 2

The previousSetBit(int fromIndex) method returns -1 if the specified index is negative.

Output:

bitset: {0, 1, 3, 4}
previous set bit previous to -1: -1