flip()
is an instance method of the BitSet
which is used to
set the bit to the complement of its current value. There are two variants of the method. These are:
flip(int bitIndex)
flip(int fromIndex, int toIndex)
The flip()
method is defined in the BitSet
class. The BitSet
class is defined in the java.util
package. To import the BitSet
class, run the following import statement.
import java.util.BitSet;
The flip(int bitIndex)
method is used to set the bit at the specified index to the complement of its current value. There are two variants of the method.
public void flip(int bitIndex)
int bitIndex
: The bit index to flip.This method does not return anything.
import java.util.Arrays;import java.util.BitSet;public class Main{public static void main(String[] args) {// Create empty BitSet objectBitSet bitSet = new BitSet();// Set the bit at index 2bitSet.set(2);// Set the bit at index 3bitSet.set(3);System.out.println("Before flip - " + bitSet);int indexToFlip = 3;// Flip the bit at index 3bitSet.flip(indexToFlip);System.out.println("After flip at " + indexToFlip + " - " + bitSet);}}
The flip(int fromIndex, int toIndex)
method is used to set each bit, from the specified fromIndex
(inclusive) to the specified toIndex
(exclusive), to the complement of its current value.
public void flip(int fromIndex, int toIndex)
int fromIndex
: The first-bit index to flip.int toIndex
: The last-bit index to flip.This method does not return anything.
import java.util.Arrays;import java.util.BitSet;public class Main{public static void main(String[] args) {// Create empty BitSet objectBitSet bitSet = new BitSet();// Set the bit at index 2bitSet.set(2);// Set the bit at index 3bitSet.set(3);System.out.println("Before flip - " + bitSet);// starting index to flipint fromIndexToFlip = 1;// ending index to flipint toIndexToFlip = 4;// Flip the bitsbitSet.flip(fromIndexToFlip, toIndexToFlip);System.out.printf("After flip from %s to %s - %s", fromIndexToFlip, toIndexToFlip, bitSet);}}