BitSet previousClearBit(int) in Java

previousClearBit(int): This method is available in java.util.BitSet class of Java.

Syntax:

int java.util.BitSet.previousClearBit(int fromIndex)

This method takes one argument of type int as its parameter. This method returns the index of the nearest bit that is set to false that occurs on or before the specified starting index.

Note: If no such bit exists, or if -1 is given as the starting index, then -1 is returned.

Parameters: One parameter is required for this method.

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

Returns: the index of the previous clear bit, or -1 if there is no such bit.

Throws:

IndexOutOfBoundsException - if the specified index is less than -1.

Approach 1: When no exception

Java

import java.util.BitSet;

public class BitSetpreviousClearBit {
    public static void main(String[] args) {
        BitSet bitSet = new BitSet(4);

        bitSet.set(1);

        bitSet.set(5);
        bitSet.set(6);
        bitSet.set(10);

        int fromIndex = 5;
        System.out.println(bitSet.previousClearBit(fromIndex));
    }
}

Output:

4


Approach 2: IndexOutOfBoundsException 

Java

import java.util.BitSet;

public class BitSetpreviousClearBit {
    public static void main(String[] args) {
        BitSet bitSet = new BitSet(4);

        bitSet.set(1);

        bitSet.set(5);
        bitSet.set(6);
        bitSet.set(10);

        int fromIndex = -2;
        System.out.println(bitSet.previousClearBit(fromIndex));
    }
}

Output:

Exception in thread "main" java.lang.IndexOutOfBoundsException: fromIndex < -1: -2 at java.base/java.util.BitSet.previousClearBit(BitSet.java:829)


No comments:

Post a Comment