Wednesday, October 22, 2025
HomeLanguagesJavaBitSet size() Method in Java with Examples

BitSet size() Method in Java with Examples

The size() Method of BitSet class in Java is used to know the size of this BitSet. This size is equal to the number of bits, each element has occupied in the BitSet. The maximum element in the set is the size – the first element

Syntax:

BitSet.hashCode()

Parameters: The method does not accept any parameters.

Return Value: The method returns the number of bits present in the BitSet.

Below programs are used to illustrate the working of BitSet.size() Method:
Program 1:




// Java code to illustrate size()
import java.util.*;
  
public class BitSet_Demo {
    public static void main(String args[])
    {
        // Creating an empty BitSet
        BitSet init_bitset = new BitSet();
  
        // Use set() method to add elements into the Set
        init_bitset.set(40);
        init_bitset.set(25);
        init_bitset.set(31);
        init_bitset.set(100);
        init_bitset.set(53);
  
        // Displaying the BitSet
        System.out.println("BitSet: " + init_bitset);
  
        // Displaying the size
        System.out.println("The size is: "
                           + init_bitset.size());
    }
}


Output:

BitSet: {25, 31, 40, 53, 100}
The size is: 128

Program 2:




// Java code to illustrate size()
import java.util.*;
  
public class BitSet_Demo {
    public static void main(String args[])
    {
        // Creating an empty BitSet
        BitSet init_bitset = new BitSet();
  
        // Displaying the BitSet
        System.out.println("BitSet: " + init_bitset);
  
        // Displaying the hashcode
        System.out.println("The s iizes: "
                           + init_bitset.size());
    }
}


Output:

BitSet: {}
The size is: 64

Program 3:




// Java code to illustrate size()
import java.util.*;
  
public class BitSet_Demo {
    public static void main(String args[])
    {
        // Creating an empty BitSet
        BitSet init_bitset = new BitSet();
  
        // Use set() method to add elements into the Set
        init_bitset.set(400);
  
        // Displaying the BitSet
        System.out.println("BitSet: " + init_bitset);
  
        // Displaying the hashcode
        System.out.println("The sizeis: " + init_bitset.size());
    }
}


Output:

BitSet: {400}
The size is: 448
RELATED ARTICLES

Most Popular

Dominic
32361 POSTS0 COMMENTS
Milvus
88 POSTS0 COMMENTS
Nango Kala
6728 POSTS0 COMMENTS
Nicole Veronica
11892 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11954 POSTS0 COMMENTS
Shaida Kate Naidoo
6852 POSTS0 COMMENTS
Ted Musemwa
7113 POSTS0 COMMENTS
Thapelo Manthata
6805 POSTS0 COMMENTS
Umr Jansen
6801 POSTS0 COMMENTS