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.

Syntax:

    public int nextSetBit(int src_in);

Parameter(s):

  • 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.

Example:

// 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 
        bs.set(10);
        bs.set(20);
        bs.set(30);
        bs.set(40);
        bs.set(50);

        // 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);
    }
}

Output

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


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.