Java Utility Library

Java BitSet - and() Method



The java.util.BitSet.and() method is used to perform a logical AND operation on the given BitSet with the argument BitSet. The given BitSet is modified so that each bit in it has the value true if both BitSets initially had the value true for the corresponding bit.

Syntax

public void and(BitSet set)

Parameters

set Specify the BitSet.

Return Value

void type.

Exception

NA

Example:

In the example below, the java.util.BitSet.and() method is used to perform a logical AND operation on the given BitSet called BSet1 with the argument BitSet BSet2.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating BitSets
    BitSet BSet1 = new BitSet();
    BitSet BSet2 = new BitSet();

    //populating BSet1
    BSet1.set(10);
    BSet1.set(20);
    BSet1.set(30);
    BSet1.set(40);
    BSet1.set(50);

    //populating BSet2
    BSet2.set(20);
    BSet2.set(40);
    BSet2.set(60);
    BSet2.set(80);
    BSet2.set(100);    

    //printing BitSet
    System.out.println("Before AND operation.");
    System.out.println("BSet1 contains: " + BSet1);

    //Performing AND operation on BSet1 using BSet2
    BSet1.and(BSet2);

    //printing BitSet
    System.out.println("\nAfter AND operation."); 
    System.out.println("BSet1 contains: " + BSet1);   
  }
}

The output of the above code will be:

Before AND operation.
BSet1 contains: {10, 20, 30, 40, 50}

After AND operation.
BSet1 contains: {20, 40}

❮ Java.util - BitSet