Collections: BitSet.flip toggles a whole range of bits at once

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.

Code
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);
Output
Before flip: {0, 1, 2, 3, 4}
After flip(2,8): {0, 1, 5, 6, 7}
Advertisement
More in JAVA

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

© Java Coding Hub · About · Contact · Privacy · Terms