Home » Java programming language

Java BitSet nextSetBit() Method with Example

BitSet Class nextSetBit() method: Here, we are going to learn about the nextSetBit() method of BitSet Class with its syntax and example.
Submitted by Preeti Jain, on January 22, 2020

BitSet Class nextSetBit() method

  • nextSetBit() method is available in java.util package.
  • nextSetBit() method is used to retrieve the index of the first bit that is set to true that occurs or searching starts after the given src_in.
  • nextSetBit() method is a non-static method, so it is accessible with the class object and if we try to access the method with the class name then we will get an error.
  • nextSetBit() method may throw an exception at the time of checking the given index.
    IndexOutOfBoundsException: This exception may throw when the given index is less than 0.


    public int nextSetBit(int src_in);


  • int src_in – represents the searching index (src_in) to start searching from.

Return value:

The return type of this method is int, it returns the index of first set bit to true or next set bit.


// Java program to demonstrate the example 
// of int nextSetBit(int src_in) method of BitSet.

import java.util.*;

public class NextSetBitOfBitSet {
    public static void main(String[] args) {
        // create an object of BitSet
        BitSet bs = new BitSet(10);

        // By using set() method is to set
        // the values in BitSet 

        // Display Bitset
        System.out.println("bs: " + bs);

        // By using nextSetBit(int) method is to return 
        // the first bit after the given index
        int next_set_bit = bs.nextSetBit(2);

        // Display next_set_bit
        System.out.println("bs.nextSetBit(2): " + next_set_bit);


bs: {10, 20, 30, 40, 50}
bs.nextSetBit(2): 10

Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.