BitSet bits = new BitSet(8); // create a bit set of size 8 bits.set(1); // set bit 1 to 1, leaving the rest at 0 bits.set(3); System.out.println("Before flip: " + bits); // prints {1, 3} bits.flip(); System.out.println("After flip: " + bits); // prints {0, 2, 4, 5, 6, 7}
BitSet bits1 = new BitSet(5); BitSet bits2 = new BitSet(5); bits1.set(0); bits1.set(1); bits2.set(2); bits2.set(3); System.out.println("Before flip:"); System.out.println("bits1: " + bits1); // prints {0, 1} System.out.println("bits2: " + bits2); // prints {2, 3} bits1.flip(2, 4); bits2.flip(1, 4); System.out.println("After flip:"); System.out.println("bits1: " + bits1); // prints {0, 1, 4} System.out.println("bits2: " + bits2); // prints {0, 2}Here, two BitSets are created and some bits are set. flip() is then called on a range of bits in each BitSet - in bits1, bits 2 and 3 are flipped, and in bits2, bits 1, 2, and 3 are flipped. After the flips, the contents of each BitSet are printed. The BitSet class is part of the Java standard library and can be found in the java.util package.