BitSet get(int) in Java

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

Syntax:

boolean java.util.BitSet.get(int bitIndex)

This method takes one argument of type int as its parameter. This method returns the value of the bit with the specified index.

Note: The value is true if the bit with the index bitIndexis currently set in this BitSet; otherwise, the result is false.

Parameters: One parameter is required for this method.

bitIndex: the bit index.

Returns: the value of the bit with the specified index.

Throws:

IndexOutOfBoundsException - if the specified index is negative.

Approach 1: When no exception

Java

import java.util.BitSet;

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

        bitSet.set(1);

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

        int bitIndex = 1;

        System.out.println(bitSet.get(bitIndex));
    }
}

Output:

true


Approach 2: IndexOutOfBoundsException

Java

import java.util.BitSet;

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

        bitSet.set(1);

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

        int bitIndex = -1;

        System.out.println(bitSet.get(bitIndex));
    }
}

Output:

Exception in thread "main" java.lang.IndexOutOfBoundsException: bitIndex < 0: -1 at java.base/java.util.BitSet.get(BitSet.java:626)


No comments:

Post a Comment