BigInteger testBit() Method in Java

prerequisite : BigInteger Basics
The java.math.BigInteger.testBit(index) method returns true if and only if the designated bit is set. This method Computes (this & (1<<n)) != 0).


public boolean testBit(int n)

Parameter: The method takes one parameter n of integer type which refers to the index of the bit that needs to be tested.

Return Value: The method returns true if and only if the designated bit is set else it will return false.

Exception: The method will throw an ArithmeticException when n is negative.

Input: BigInteger = 2300, n = 4
Output: true
Binary Representation of 2300 = 100011111100
bit at index 4 is 1 so set it means bit is set
so method will return true

Input: BigInteger = 5482549 , n = 1
Output: false

Below program illustrates the testBit() method of BigInteger.





// Program to demonstrate the testBit()
// method of BigInteger
import java.math.*;
public class GFG {
    public static void main(String[] args)
        // Creating a BigInteger object
        BigInteger biginteger = new BigInteger("2300");
        // Creating an int i for index
        int i = 3;
        boolean flag = biginteger.testBit(i);
        String result = "The bit at index " + i + " of "
        biginteger + " is set = " + flag;
        // Displaying the result



The bit at index 3 of 2300 is set = true


Attention reader! Don’t stop learning now. Get hold of all the important Java and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up

I am a Developer I love to code and bring my ideas alive

If you like GeeksforGeeks and would like to contribute, you can also write an article using or mail your article to See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.