Java.math.BigInteger.testBit() Method



Description

The java.math.BigInteger.testBit(int n) returns true if and only if the designated bit is set. It computes (this & (1<<n)) != 0).

Declaration

Following is the declaration for java.math.BigInteger.testBit() method.

public boolean testBit(int n)

Parameters

n − index of bit to test

Return Value

This method returns true if and only if the designated bit of this BigInteger is set.

Exception

ArithmeticException − n is negative

Example

The following example shows the usage of math.BigInteger.testBit() method.

package com.tutorialspoint;

import java.math.*;

public class BigIntegerDemo {

   public static void main(String[] args) {

      // create a BigInteger object
      BigInteger bi;

      // create 2 boolean objects
      Boolean b1, b2;

      bi = new BigInteger("10"); 

      // perform testbit on bi at index 2 and 3
      b1 = bi.testBit(2);
      b2 = bi.testBit(3);

      String str1 = "Test Bit on " + bi + " at index 2 returns " +b1;
      String str2 = "Test Bit on " + bi + " at index 3 returns " +b2;

      // print b1, b2 values
      System.out.println( str1 );
      System.out.println( str2 );
   }
}

Let us compile and run the above program, this will produce the following result −

Test Bit on 10 at index 2 returns false
Test Bit on 10 at index 3 returns true
java_math_biginteger.htm
Advertisements