Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
communitycreator

What is BitSet.flip() in Java?

abhilash

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;

flip(int bitIndex)

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)

Parameters

  • int bitIndex: The bit index to flip.

Return value

This method does not return anything.

Code

import java.util.Arrays;
import java.util.BitSet;

public class Main{

    public static void main(String[] args) {
        // Create empty BitSet object
        BitSet bitSet = new BitSet();

        // Set the bit at index 2
        bitSet.set(2);

        // Set the bit at index 3
        bitSet.set(3);

        System.out.println("Before flip - " + bitSet);

        int indexToFlip = 3;

        // Flip the bit at index 3
        bitSet.flip(indexToFlip);

        System.out.println("After flip at " + indexToFlip + " - " + bitSet);
        
    }
}
Calling bitSet.flip() method

flip(int fromIndex, int toIndex)

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)

Parameters

  • int fromIndex: The first-bit index to flip.
  • int toIndex: The last-bit index to flip.

Return value

This method does not return anything.

Code

import java.util.Arrays;
import java.util.BitSet;

public class Main{

    public static void main(String[] args) {
        // Create empty BitSet object
        BitSet bitSet = new BitSet();

        // Set the bit at index 2
        bitSet.set(2);

        // Set the bit at index 3
        bitSet.set(3);

        System.out.println("Before flip - " + bitSet);

        // starting index to flip
        int fromIndexToFlip = 1;

        // ending index to flip
        int toIndexToFlip = 4;

        // Flip the bits
        bitSet.flip(fromIndexToFlip, toIndexToFlip);

        System.out.printf("After flip from %s to %s - %s", fromIndexToFlip, toIndexToFlip, bitSet);

    }
}
Calling bitSet.flip() method with from and to index

RELATED TAGS

java
communitycreator
RELATED COURSES

View all Courses

Keep Exploring