java.math.BigInteger flipBit(int n)


On this document we will be showing a java example on how to use the flipBit(int n) method of BigInteger Class. Basically this method returns a BigInteger whose value is equivalent to this BigInteger with the designated bit flipped. (Computes (this ^ (1<<n)).)

Let’s take a for example a BigInteger 12 which is equivalent to binary 1100. So if we have a value n=2, then the Binary equivalent would become 1000. Remember that the counting starts 0 index. Binary 1000 is equal to 8 in BigInteger so that would be the returned value.


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

Method Syntax

public BigInteger flipBit(int n)

Method Argument

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

Method Returns

The flipBit() method this ^ (1<<n).


Requires Java 1.1 and up

Java BigInteger flipBit() Example

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


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

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

public class BigIntegerFlipBitExample {

	public static void main(String[] args) {	
		// initialize a BigInteger object		
		BigInteger val1 = new BigInteger("19");
		 * Note: 19 in binary is 10011
		// get user input
		System.out.print("Enter the bit number you want to flip:");
		Scanner s = new Scanner(;
		String input = s.nextLine();		
		 * convert the input to Integer
		 * unboxing feature will be used 
		 * to transform Integer to primitive int
		Integer inputBitNumber = Integer.parseInt(input);

		// get the new BigInteger 
		BigInteger result = val1.flipBit(inputBitNumber);
		System.out.println("Result of the operation:"+result);


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 be flipped. When we say bit flipping is that 0 becomes 1 and vice versa. Using the initially declared BigInteger and the index provided by the user, we will be using simulating the behavior of the flipBit() method.

Sample Output

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

BigInteger flipBit() example output