BitSet nextClearBit(int) in Java

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

Syntax:

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

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

Parameters: One parameter is required for this method.

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

Returns: the index of the next clear bit.

Throws:

IndexOutOfBoundsException - if the specified index is negative.

Approach 1: When no exception

Java

import java.util.BitSet;

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

        bitSet.set(1);

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

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

Output:

7


Approach 2: IndexOutOfBoundsException 

Java

import java.util.BitSet;

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

        bitSet.set(1);

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

        int fromIndex = -1;
        System.out.println(bitSet.nextClearBit(fromIndex));
    }
}

Output:

Exception in thread "main" java.lang.IndexOutOfBoundsException: fromIndex < 0: -1 at java.base/java.util.BitSet.nextClearBit(BitSet.java:747)



No comments:

Post a Comment