# BitSet int previousSetBit(int fromIndex) Method Example Program

Returns the index of the nearest bit that is set to true that occurs on or before the specified starting index. If no such bit exists, or if -1 is given as the starting index, then -1 is returned.
To iterate over the true bits in a BitSet, use the following loop:

for (int i = bs.length(); (i = bs.previousSetBit(i-1)) >= 0; ) {
// operate on index i here
}

#### Program

```package com.candidjava;

import java.util.BitSet;

/**
* @author : vinod kumar v
* @description :previousSetBit(int fromIndex) Returns the index of the nearest
*              bit that is set to true that occurs on or before the specified
*              starting index.
* */

public final class BitSetPreviousSet {
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 previousset bit is:" + obj.previousSetBit(0));
System.out.println(" the previousset bit is:" + obj1.previousSetBit(6));
}
}
```

#### Output

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

#### Explanation

public int previousSetBit(int fromIndex)
Returns the index of the nearest bit that is set to true that occurs on or before the specified starting index. If no such bit exists, or if -1 is given as the starting index, then -1 is returned.
To iterate over the true bits in a BitSet, use the following loop:

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

Related Post