java.math.BigInteger testBit(int n)

Description

On this document we will be showing a java example on how to use the testBit(int n) method of BigInteger Class. Basically this method returns a boolean, true if the bit corresponding to the method argument n as index has been set, otherwise false. What I mean when I say the bit is set is that the bit number is set to 1. Let’s say for example we have BigInteger 12 which has an equivalent binary value as 1100. So if we test the bit on index 2, the result would be true. Don’t get confused on the count of index, always remember that index count starts at 0 from right to left.

Notes:

  • this method throws an Arithmetic exception if n supplied is negative.

Method Syntax

public boolean testBit(int n)

Method Argument

Data Type Parameter Description
int n index of bit to test.

Method Returns

The testBit() method return true if and only if the designated bit is set.

Compatibility

Requires Java 1.1 and up

Java BigInteger testBit(int n) Example

Below is a java code demonstrates the use of testBit(int n) method of BigInteger class. The example presented might be simple however it shows the behavior of the testBit(int n) method.

package com.javatutorialhq.java.examples;

import java.math.BigInteger;
import java.util.Scanner;

/*
 * A java example source code to demonstrate
 * the use of testBit(int n) method of BigInteger class
 */

public class BigIntegerTestBitExample {

	public static void main(String[] args) {

		// initialize a BigInteger object
		BigInteger val1 = new BigInteger("17");
		/*
		 * Note: 17 in binary is 10001
		 */

		// get user input
		System.out.print("Enter the bit number you want to test:");
		Scanner s = new Scanner(System.in);
		String input = s.nextLine();
		s.close();

		/*
		 * convert the input to Integer, unboxing feature will be used to
		 * transform Integer to primitive int
		 */
		Integer inputBitNumber = Integer.parseInt(input);

		// test if the index specified is set
		boolean result = val1.testBit(inputBitNumber);
		if(result){
			System.out.println("The bit specified is set");
		}else{
			System.out.println("The bit specified is not set");
		}
	}

}

This example is a lot simpler than it looks. The first part is the declaration of a BigInteger. User are then asked to provide the index of bit to test. The result is evaluated by testing the output of testBit using if condition. If the result is true, a message “The bit specified is set” otherwise a message “The bit specified is not set” is printed on the console.

Sample Output

Below is the sample output when you run the above example.

BigInteger testBit() example output