Java BigInteger Class | flipBit() Method with Example

BigInteger Class flipBit() method: Here, we are going to learn about the flipBit() method of BigInteger Class with its syntax and example.
Submitted by Preeti Jain, on May 10, 2020

BigInteger Class flipBit() method

  • flipBit() method is available in java.math package.
  • flipBit() method is used to flip the bit indexed at the given position in this BigInteger.
  • flipBit() method is a non-static method, it is accessible with the class object only and if we try to access the method with the class name then we will get an error.
  • flipBit() method may throw an exception at the time of flipping a particular bit.
    ArithmeticException: This exception may throw when the given parameter holds a negative value.

Syntax:

    public BigInteger flipBit(int pos);

Parameter(s):

  • int pos – represents the index of flipped bit.

Return value:

The return type of this method is BigInteger, it returns BigInteger that holds the value flipped bit at the given position in this BigInteger.

Example:

// Java program to demonstrate the example 
// of BigInteger flipBit(int pos) method of BigInteger

import java.math.*;

public class FlipBitOfBI {
    public static void main(String args[]) {
        // Initialize a variable str
        String str = "10";

        // Initialize a BigInteger object 
        BigInteger b_int = new BigInteger(str);

        // Display b_int
        System.out.println("b_int: " + b_int);

        // Display Binary representation of str 
        System.out.println("Binary Representation of 10: 1010 ");

        // flips the bit value at the
        // given indices in this BigInteger 
        // b_int, here the bit set "1" at the given
        // indices(1) so the bit is flipped from "1" to "0"
        // so the binary representation of 10 was 1010 before
        // flip and after flipBit(1) the representation 
        // is 1000
        BigInteger flip_bit = b_int.flipBit(1);
        System.out.println("b_int.flipBit(1): " + flip_bit);
        System.out.println("Binary Representation of 8: 1000 ");

        // flips the bit value at the
        // given indices in this BigInteger 
        // b_int, here the bit set "0" at the given
        // indices(0) so the bit is flipped from "0" to "1"
        // so the binary representation of 10 was 1010 before
        // flip and after flipBit(0) the representation 
        // is 1011
        flip_bit = b_int.flipBit(0);
        System.out.println("b_int.flipBit(0): " + flip_bit);
        System.out.println("Binary Representation of 11: 1011 ");
    }
}

Output

b_int: 10
Binary Representation of 10: 1010 
b_int.flipBit(1): 8
Binary Representation of 8: 1000 
b_int.flipBit(0): 11
Binary Representation of 11: 1011 



Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.