Java BitSet flip() method

The flip() method of Java BitSet class sets the bit set to its complement. For example, if a bit value contains a true value then if you apply flip() operation on it, it will return false.

There are two overloaded flip() method available in BitSet class. These methods are differentiated on the basis of its parameter.

1. Java BitSet flip(int bitIndex) method

The flip(int bitIndex) method sets the bit to its complement at the specified index.

2. Java BitSet flip(int fromIndex, int toIndex) method

The flip(int fromIndex, int toIndex) method set each bit value to its complement from specified inclusive fromIndex to exclusive toIndex.

Syntax:

Parameter:

DataTypeParameterDescription
intbitIndexIt is an index of BitSet which is to be flip.
intfromIndexIt is an index of BitSet from which the flips of bits start.
inttoIndexIt is an exclusive index of BitSet at which the flips of bits end.

Returns:

NA

Exception:

MethodException
flip(int bitIndex)IndexOutOfBoundsException - if the specified index of bit set is negative.
flip(int fromIndex, int toIndex)IndexOutOfBoundsException = if any of the fromIndex or toIndex are negative, or fromIndex is larger than toIndex.

Compatibility Version:

Java 1.4 and above

Example of Java BitSet flip(int bitIndex) method

Example 1

Output:

bitset: {0, 1, 2, 3}
bitset value: true true true true
bitset after flip index 1: {0, 2, 3}
bitset value after flip index 1: true false true true

Example 2

The flip(int bitIndex) method throw IndexOutOfBoundsException if we provide negative index value.

Output:

Exception in thread "main" java.lang.IndexOutOfBoundsException: bitIndex < 0: -1
	at java.util.BitSet.flip(Unknown Source)
	at BitSetFlipExample2.main(BitSetFlipExample2.java:12)
bitset: {0, 1, 2, 3}
bitset value: true true true true

Example of Java BitSet flip(int fromIndex, int toIndex) method

Example 3

Output:

bitset: {0, 1, 2, 3, 5}
bitset value: true true true true true
bitset after flip index 1,3: {0, 3, 5}
bitset value after flip index 1,3: true false false true true

Example 4

The flip(int fromIndex, int toIndex) method throw IndexOutOfBoundsException if toIndex is greater than fromIndex.

Output:

Exception in thread "main" java.lang.IndexOutOfBoundsException: fromIndex: 3 > toIndex: 1
	at java.util.BitSet.checkRange(Unknown Source)
	at java.util.BitSet.flip(Unknown Source)
	at BitSetFlipExample4.main(BitSetFlipExample4.java:13)
bitset: {0, 1, 2, 3, 5}
bitset value: true true true true true