BitSet flip(int) in Java

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

Syntax:

void java.util.BitSet.flip(int bitIndex)

This method takes one argument of type int as its parameter. This method sets the bit at the specified index to the complement of its current value.

Parameters: One parameter is required for this method.

bitIndex: the index of the bit to flip.

Throws:

IndexOutOfBoundsException - if the specified index is negative.

Approach 1: When no exception

Java

import java.util.BitSet;

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

        bitSet.set(1);

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

        int bitIndex = 1;
        bitSet.flip(bitIndex);
        System.out.println(bitSet.clone());
    }
}

Output:

{5, 6, 10}


Approach 2: IndexOutOfBoundsException 

Java

import java.util.BitSet;

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

        bitSet.set(1);

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

        int bitIndex = -1;
        bitSet.flip(bitIndex);
        System.out.println(bitSet.clone());
    }
}

Output:

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


No comments:

Post a Comment