Saturday, December 13, 2025
HomeLanguagesJavaBigInteger testBit() Method in Java

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

Syntax:

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.
Examples:

Input: BigInteger = 2300, n = 4
Output: true
Explanation:
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
        System.out.println(result);
    }
}


Output:

The bit at index 3 of 2300 is set = true

Reference: https://docs.oracle.com/javase/7/docs/api/java/math/BigInteger.html#testBit(int)

Dominic
Dominichttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Dominic
32447 POSTS0 COMMENTS
Milvus
105 POSTS0 COMMENTS
Nango Kala
6815 POSTS0 COMMENTS
Nicole Veronica
11952 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12031 POSTS0 COMMENTS
Shaida Kate Naidoo
6951 POSTS0 COMMENTS
Ted Musemwa
7202 POSTS0 COMMENTS
Thapelo Manthata
6898 POSTS0 COMMENTS
Umr Jansen
6882 POSTS0 COMMENTS