BitSet set(int, boolean) in Java

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

Syntax:

void java.util.BitSet.set(int bitIndex, boolean value)

This method takes two arguments one of type int and the other of type boolean as its parameters. This method sets the bit at the specified index to the specified value.

Parameters: Two parameters are required for this method.

bitIndex: a bit index.

value: a boolean value to set.

Throws:

IndexOutOfBoundsException - if the specified index is negative.

Approach 1: When no exception

Java


Output:

{10}


Approach 2: IndexOutOfBoundsException 

Java

import java.util.BitSet;

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

        int bitIndex = -1;
        boolean value = false;
        bitSet.set(bitIndex, value);
        bitSet.set(10);

        System.out.println(bitSet);
    }
}

Output:

Exception in thread "main" java.lang.IndexOutOfBoundsException: bitIndex < 0: -1 at java.base/java.util.BitSet.clear(BitSet.java:543) at java.base/java.util.BitSet.set(BitSet.java:469)


No comments:

Post a Comment