What is BitSet.clear() in Java?

Overview

clear() is an instance method of the BitSet class that is used to set bits to false. There are three variations of the clear method:

  • clear(int bitIndex)
  • clear()
  • clear(int fromIndex, int toIndex)

The clear method is defined in the BitSet class. The BitSet class is defined in the java.util package. To import the BitSet class, use the following import statement.

import java.util.BitSet;

The clear(int bitIndex) method

The clear(int bitIndex) method sets the bit value at the given index to false.


public void clear(int bitIndex)

Parameters

  • int bitIndex: The bit index.

Return value

This method does not return anything.

Code

import java.util.Arrays;
import java.util.BitSet;
public class Main{
public static void main(String[] args) {
// Create empty BitSet object
BitSet bitSet = new BitSet();
// Set the bit at index 2
bitSet.set(2);
// Set the bit at index 143
bitSet.set(143);
// Bit object before clearing bit at index 2
System.out.printf("Before clear - %s" , bitSet);
System.out.println("\n----");
// clear bit at index 2
bitSet.clear(2);
// Bit object after clearing bit at index 2
System.out.printf("After clear - %s" , bitSet);
}
}

The clear() method

The clear() method sets all the bits to false.


public void clear()

Parameters

The method has no parameters.

Return value

The clear method does not return anything.

Code

import java.util.Arrays;
import java.util.BitSet;
public class Main{
public static void main(String[] args) {
// Create empty BitSet object
BitSet bitSet = new BitSet();
// Set the bit at index 2
bitSet.set(2);
// Set the bit at index 143
bitSet.set(143);
// Bit object before clearing all bits
System.out.printf("Before clear - %s" , bitSet);
System.out.println("\n----");
// clear all bits
bitSet.clear();
// Bit object after clearing all bits
System.out.printf("After clear - %s" , bitSet);
}
}

The clear(int fromIndex, int toIndex) method

The clear(int fromIndex, int toIndex) method sets the bit values from the specified fromIndex (inclusive) to the specified toIndex (exclusive) to false.


public void clear(int fromIndex, int toIndex)

Parameters

  • int fromIndex: The first-bit index.
  • int toIndex: The last-bit index.

Return value

This method does not return anything.

Code

import java.util.Arrays;
import java.util.BitSet;
public class Main{
public static void main(String[] args) {
// Create empty BitSet object
BitSet bitSet = new BitSet();
// Set the bit at index 2
bitSet.set(2);
// Set the bit at index 3
bitSet.set(3);
// Set the bit at index 143
bitSet.set(143);
// Bit object before clearing
System.out.printf("Before clear - %s" , bitSet);
System.out.println("\n----");
int fromIndex = 2;
int toIndex = 5;
// clear bits from index 2 to 5
bitSet.clear(fromIndex, toIndex);
// Bit object after clearing
System.out.printf("After clear - %s" , bitSet);
}
}

Free Resources