Working With BitSet Class in Java


In this article we are going to describe one of the important classes of the util package in Java. So we explain the use of the BitSet class test; also what is the need of the bit class. A BitSet class creates a special type of array that holds bit values. This array can increase in size as needed. This makes it similar to a vector of bits.

BitSet Class

The BitSet class implements a vector of bits that can grow as needed. Each component of the bit set has a boolean value. The bits of a BitSet are indexed by nonnegative integers. Individual indexed bits can be examined, set, or cleared. One BitSet may be used to modify the contents of another BitSet through logical AND, logical inclusive OR, and logical exclusive OR operations.

Note : By default, all bits in the set initially have the value false. And something else to be concerned with is that when you pass a null parameter to any of the methods in a BitSet, that will result in a NullPointerException. A BitSet is not safe for multithreaded use without external synchronization.

BitSet Class Structure

public class BitSet extends Object implements Cloneable, Serializable

Constructor Details

This class contains two constructors; one is a default constructor for creating default objects of a BitSet class and another is a constructor that takes as an int type one argument whose initial size is large enough to explicitly represent the bits with indices in the range 0 through nbits-1. All bits are initially false.

public BitSet()

public BitSet(int nbits)

Methods Details :



Example :

import java.util.BitSet;


class MyBitSetDemo {

      public static void main(String args[]) {

            BitSet bits1 = new BitSet(12);

            BitSet bits2 = new BitSet(24);

            // set some bits

            for (int i = 10; i < 32; i++) {

                  if ((i % 2) == 0)


                  if ((i % 5) != 0)



            System.out.println(“Initial  bits1: “);


            System.out.println(“\\nInitial bits2: “);


            // AND bits


            System.out.println(“\\nbits2 AND bits1: “);


            // OR bits


            System.out.println(“\\nbits2 OR bits1: “);


            // XOR bits


            System.out.println(“\\nbits2 XOR bits1: “);





bitset cmd.jpg


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s