Java Utility Library

Java BitSet - flip() Method



The java.util.BitSet.flip() method is used to set each bit from the specified fromIndex (inclusive) to the specified toIndex (exclusive) to the complement of its current value in the given BitSet.

Syntax

public void flip(int fromIndex, int toIndex)

Parameters

fromIndex Specify the index of the first bit to flip.
toIndex Specify the index after the last bit to flip.

Return Value

void type.

Exception

Throws IndexOutOfBoundsException, if fromIndex is negative, or toIndex is negative, or fromIndex is larger than toIndex.

Example:

In the example below, the java.util.BitSet.flip() method is used to flip the bit for a range of index in the given BitSet.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating a BitSet
    BitSet BSet = new BitSet();

    //populating the BitSet
    BSet.set(10);
    BSet.set(20);
    BSet.set(30);
    BSet.set(40);
    BSet.set(50);

    //printing the BitSet
    System.out.println("BSet contains: " + BSet);

    //flipping the bit for range [27, 33)
    BSet.flip(27, 33);

    //printing the BitSet
    System.out.println("BSet contains: " + BSet);
  }
}

The output of the above code will be:

BSet contains: {10, 20, 30, 40, 50}
BSet contains: {10, 20, 27, 28, 29, 31, 32, 40, 50}

❮ Java.util - BitSet