What is the BitSet.and() method in Java?

The and() function of the BitSet class in Java is used to perform the logical AND operation.

We can invoke this method by using the dot (.) operator on the invoking object, which will then perform the AND operation with the BitSet object provided as an argument.

The result of the AND operation will be visible through the invoking object.

Syntax


public void and(BitSet bitset)

To use this method, you must import the java.util.BitSet class in your program, as shown below.

import java.util.BitSet

Parameters

bitset: An instance or object of the BitSet class.

Return value

This method does not return any value.

Code

The code below shows how the and() function works in Java.

Tip: Execute this code multiple times for different results.

import java.util.BitSet;
import java.util.Random;
class EdPresso {
public static void main( String args[] ) {
// object for Random Class
Random rand = new Random();
// objects of BitSet Class
BitSet bitset1 = new BitSet(15);
BitSet bitset2 = new BitSet(15);
// set some bits
for(int i = 0; i < 10; i++) {
bitset1.set(rand.nextInt(30));
bitset2.set(rand.nextInt(30));
}
System.out.println("bitset1: ");
System.out.println(bitset1);
System.out.println("\nbitset2: ");
System.out.println(bitset2);
// AND bits
bitset1.and(bitset2);
System.out.println("\nbitset1 AND bitset2: ");
System.out.println(bitset1);
}
}

Explanation

We have two BitSet objects in the code above: bitset1 and bitset2.

In line 1212, we use an object of the Random class to generate 1010 random numbers for each BitSet object.

The and() method in line 2323, bitset1.and(bitset2), returns the logical AND between bitset1 and bitset2. The result can be viewed by printing bitset1, as it is altered to store the result of the AND operation.

New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources