Monday, October 6, 2025
HomeLanguagesJavaJava.util.BitSet.flip() in Java

Java.util.BitSet.flip() in Java

There are two variants of flip() method. This article depicts about all of them as follows:

1. flip(int value) : This method removes the value specified in the argument.

public void flip(int value)

Parameters : 
value :  the value to flip.
Return ValueThis method does not return a value.




// Java code to demonstrate the
// working of flip(int value) in Bitset
  
import java.util.*;
  
public class Flip1 {
  public static void main(String[] args) {
       
  // declaring bitset
  BitSet bset = new BitSet(6);
   
  // assigning values to bset
  bset.set(0);
  bset.set(1);
  bset.set(2);
  bset.set(3);
  
  // printing the original set
  System.out.println("The original bitset is : " + bset);
   
  // using flip() to remove 2
  bset.flip(2);
       
  //  printing final bitset
  // 2 is removed
  System.out.println("The flipped bitset is : " + bset);
  }
}


Output:

The original bitset is : {0, 1, 2, 3}
The flipped bitset is : {0, 1, 3}

2. flip(int fromnum, int tonum) : This method sets each bit from the specified fromnum (inclusive) to the specified tonum (exclusive) to the complement of its current value, i.e removes fromnum to tonum-1 values.

public void flip(int fromnum,int tonum)
Parameters : 
fromnum :  start number to begin flipping.
tonum :  last-1 number to end flipping.
Return Value : 
This method does not return a value.




// Java code to demonstrate the
// working of flip(int fromnum, int tonum) in Bitset
  
import java.util.*;
  
public class Flip2 {
  public static void main(String[] args) {
       
  // declaring bitset
  BitSet bset = new BitSet(6);
   
  // assigning values to bset
  bset.set(0);
  bset.set(1);
  bset.set(2);
  bset.set(3);
  
  // printing the original set
  System.out.println("The original bitset is : " + bset);
   
  // using flip(fromnum,tonum) to remove 1 and 2
  bset.flip(1,3);
       
  //  printing final bitset
  // 1 and 2 are removed
  System.out.println("The flipped bitset is : " + bset);
  }
}


Output:

The original bitset is : {0, 1, 2, 3}
The flipped bitset is : {0, 3}

This article is contributed by Astha Tyagi. If you like Lazyroar and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the Lazyroar main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

RELATED ARTICLES

Most Popular

Dominic
32337 POSTS0 COMMENTS
Milvus
86 POSTS0 COMMENTS
Nango Kala
6707 POSTS0 COMMENTS
Nicole Veronica
11871 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11936 POSTS0 COMMENTS
Shaida Kate Naidoo
6823 POSTS0 COMMENTS
Ted Musemwa
7089 POSTS0 COMMENTS
Thapelo Manthata
6779 POSTS0 COMMENTS
Umr Jansen
6779 POSTS0 COMMENTS