flip(from, to) inverts every bit in that half-open range in one call, turning set bits off and clear bits on, which is handy for negating a mask without a manual loop.
BitSet bits = new BitSet();
bits.set(0, 5);
System.out.println("Before flip: " + bits);
bits.flip(2, 8);
System.out.println("After flip(2,8): " + bits);
Before flip: {0, 1, 2, 3, 4}
After flip(2,8): {0, 1, 5, 6, 7}
Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.
Published 2026-09-27