Java BitSet get() method

The get() method of Java BitSet class returns the bit value. There are two overloaded get() method available in BitSet class.

1. Java BitSet get(int bitIndex) method

The get(int bitIndex) method returns the bit value of the specified index. It returns true if the index bitIndex is currently set in the BitSet, otherwise returns false.

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

The get(int bitIndex) method returns a new BitSet of bits from specified inclusive index fromIndex to exclusive index toIndex of the current BitSet.

Syntax:

Parameter:

DataTypeParameterDescription
intbitIndexIt is an index of bit.
intfromIndexIt is a start index of bit from which the value of bit gets.
inttoIndexIt is the exclusive end index of bit from which the value of bit gets.

Returns:

MethodDescription
get(int bitIndex)It returns the bit value of the specified index.
get(int fromIndex, int toIndex)It returns new new BitSet of bits from specified fromIndex to exclusive toIndex.

Exception:

IndexOutOfBoundsException - If any of the following statement becomes true:

  • If any of the index in negative
  • If the index fromIndex is greater than the index toIndex.

Compatibility Version:

MethodCompatibility Version
get(int bitIndex)Java 1.0 and above
get(int fromIndex, int toIndex)Java 1.4 and above

Example of Java BitSet get(int bitIndex) method

Example 1

Output:

bitset: {0, 1, 3, 4}
bitset at index 0: true
bitset at index 1: true
bitset at index 2: false

Example 2

The get(int bitIndex) method throw an exception, if passing a negative int parameter.

Output:

bitset: {0, 1, 3, 4}
Exception in thread "main" java.lang.IndexOutOfBoundsException: bitIndex < 0: -1
	at java.util.BitSet.get(Unknown Source)
	at BitSetGetExample2.main(BitSetGetExample2.java:11)

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

Example 3

Output:

bitset: {0, 1, 3, 4}
bitset at index 0,3: {0, 1}

Example 4

The get(int fromIndex, int toIndex) method throw an exception, if fromIndex is greater than the index toIndex.

Output:

bitset: {0, 1, 3, 4}
Exception in thread "main" java.lang.IndexOutOfBoundsException: fromIndex: 3 > toIndex: 0
	at java.util.BitSet.checkRange(Unknown Source)
	at java.util.BitSet.get(Unknown Source)
	at BitSetGetExample4.main(BitSetGetExample4.java:12)