Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
BitSet class methods in Java with Examples | Set 3
Next article icon

Java.util.BitSet class in Java with Examples | Set 1

Last Updated : 31 Jul, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

BitSet is a class defined in the java.util package. It creates an array of bits represented by boolean values.

Constructors: 

 BitSet class Constructors     /                  \   BitSet()          BitSet(int no_Of_Bits)
  • BitSet() : A no-argument constructor to create an empty BitSet object. 
     
  • BitSet(int no_Of_Bits): A one-constructor with an integer argument to create an instance of the BitSet class with an initial size of the integer argument representing the number of bits. 

Java




// Java program illustrating Bitset Class constructors.
import java.util.*;
public class GFG
{
    public static void main(String[] args)
    {
        // Constructors of BitSet class
        BitSet bs1 = new BitSet();
        BitSet bs2 = new BitSet(6);
 
        /* set is BitSet class method
           explained in next articles */
        bs1.set(0);
        bs1.set(1);
        bs1.set(2);
        bs1.set(4);
 
        // assign values to bs2
        bs2.set(4);
        bs2.set(6);
        bs2.set(5);
        bs2.set(1);
        bs2.set(2);
        bs2.set(3);
 
        // Printing the 2 Bitsets
        System.out.println("bs1  : " + bs1);
        System.out.println("bs2  : " + bs2);
    }
}
 
 

Output: 

bs1 : {0, 1, 2, 4} bs2 : {1, 2, 3, 4, 5, 6}

Important Points :  

  • The size of the array is flexible and can grow to accommodate additional bit as needed.
  • As it is an array, the index is zero-based and the bit values can be accessed only by non-negative integers as an index.
  • The default value of the BitSet is boolean false with a representation as 0 (off).
  • Calling the clear method makes the bit values set to false.
  • BitSet uses about 1 bit per boolean value.
  • To access a specific value in the BitSet, the get method is used with an integer argument as an index.

What happens if the array index in bitset is set as Negative?

The program will throw java.lang.NegativeArraySizeException 

Java




// Java program illustrating Exception when we access
// out of index in BitSet class.
import java.util.*;
 
public class GFG
{
    public static void main(String[] args)
    {
        // Constructors of BitSet class
        BitSet bs1 = new BitSet();
 
        // Negative array size
        BitSet bs2 = new BitSet(-1);
 
        /* set is BitSet class method
           explained in next articles */
        // assigning values to bitset 1
        bs1.set(0);
        bs1.set(1);
 
        // assign values to bs2
        bs2.set(4);
        bs2.set(6);
 
        System.out.println("bs1  : " + bs1);
        System.out.println("bs2  : " + bs2);
    }
}
 
 

Output: 

Exception in thread "main" java.lang.NegativeArraySizeException: nbits < 0: -1     at java.util.BitSet.(BitSet.java:159)     at GFG.main(NewClass.java:9)

BitSet class methods in Java with Examples | Set 2

 



Next Article
BitSet class methods in Java with Examples | Set 3

M

Mohit Gupta
Improve
Article Tags :
  • Java
  • Java - util package
  • Java-BitSet
  • Java-Library
Practice Tags :
  • Java

Similar Reads

  • Java.util.BitSet class methods in Java with Examples | Set 2
    Methods discussed in this post: BitSet class methods. / / | | \ \ set() xor() clone() clear() length() cardinality() We strongly recommend to refer below set 1 as a prerequisite of this. BitSet class in Java | Set 1 set() : java.util.BitSet.set() method is a sets the bit at the specified index to th
    4 min read
  • BitSet class methods in Java with Examples | Set 3
    BitSet class methods in Set 3. / / | | | \ \ and notand flip isEmpty equal get intersect BitSet class methods in Java with Examples | Set 2 BitSet class methods are explained as follows : and / notand : java.util.BitSet.and() and java.util.BitSet.notand() method is a java.util.Bitset class method. .
    5 min read
  • BitSet clone() Method in Java with Examples
    The clone() Method Java.util.BitSet class is used to create a copy of an existing BitSet. The new BitSet is exactly equal to the existing one and is a mere copy of the previous BitSet. Syntax: Bit_Set.clone() Parameters: The method does not take any parameters. Return Value: The method just returns
    2 min read
  • BitSet equals() Method in Java with Examples
    The equals() method of Java BitSet class is used to check for equality between two bitsets. It verifies whether the elements of one set passed as a parameter is equal to the elements of this set or not. The method returns true if the bitsets match else false. Syntax: Bit_Set1.equals(Bit_Set2) Parame
    2 min read
  • 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 pa
    2 min read
  • BitSet length() Method in Java with Examples
    The length() Method of BitSet class in Java is used to know the logical size of this BitSet. This logical size is equal to the highest bit of the BitSet plus one. Syntax: BitSet.hashCode() Parameters: The method does not accept any parameters. Return Value: The method returns the logical size of the
    2 min read
  • BitSet toString() Method in Java with Examples
    The java.util.BitSet.toString() is an inbuilt method of BitSet class that is used to get a string representation of the bits of the sets in the form of a set of entries separated by “, “. So basically the toString() method is used to convert all the elements of BitSet into String. In addition to thi
    2 min read
  • Java.util.BitSet.clear() in Java
    There are three variants of clear() method: clear() : The clear() method sets all of the bits in this BitSet to false. public void clear() Return Value This method does not return a value. // Java code to demonstrate the working // of clear() in BitSet import java.util.*; public class BitClr1 { publ
    3 min read
  • BitSet stream() Method in Java with Examples
    The stream() method of Java BitSet class is used to return a stream of indices for every bit contained in the BitSet. The indices are returned in increasing order. The size of the stream is the number of bits in the set state of the BitSet, which is equal to the value returned by the cardinality() m
    2 min read
  • BitSet toLongArray() Method in Java with Examples
    The java.util.BitSet.toLongArray() is an inbuilt method of BitSet class that is used to produce a new long array containing all of the bits of the existing BitSet. As per the official documentation, this process works in the following way: if, long[] longs = bit_set.toLongArray(); then, longs.length
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences