Java BigInteger Class | shiftRight() Method with Example

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

BigInteger Class shiftRight() method

  • shiftRight() method is available in java.math package.
  • shiftRight() method is used to shift the given number of bits to the right in this BigInteger.
  • shiftRight() 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.
  • shiftRight() method may throw an exception at the time of shifting bits.
    ArithmeticException: This exception may throw when the given parameter value holds Integer.MIN_VALUE.

Syntax:

    public BigInteger shiftRight(int number);

Parameter(s):

  • int number – represents the value in bits and when it holds negative value it performs left shift instead of right.

Return value:

The return type of this method is BigInteger, it returns BigInteger that holds the value [(this BigInteger) >>(number)].

Example:

// Java program to demonstrate the example 
// of BigInteger shiftRight(int number) method of BigInteger

import java.math.*;

public class ShiftRightOfBI {
    public static void main(String args[]) {
        // Initialize a variable str 
        // number1 and number2
        String str = "20";
        int number1 = 1;
        int number2 = -1;

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

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

        // shifts the given number of bits
        // to the right in this BigInteger b_int so
        // the value 20 << 1  it is 1/2 times the given
        // value of b_int when the given number is +ve
        // i.e. 20/2 = 10
        BigInteger shift_right = b_int.shiftRight(number1);
        System.out.println("b_int.shiftRight(+number1): ");
        System.out.println("b_int.shiftRight(+number1): " + shift_right);

        System.out.println();

        // shifts the given number of bits
        // to the right in this BigInteger b_int so
        // the value 20 << -1  it is 2 times the given
        // value of b_int when the given number is -ve
        // i.e. 20*2 = 40
        shift_right = b_int.shiftRight(number2);
        System.out.println("b_int.shiftRight(-number2): ");
        System.out.println("b_int.shiftRight(-number2): " + shift_right);
    }
}

Output

b_int: 20
b_int.shiftRight(+number1): 
b_int.shiftRight(+number1): 10

b_int.shiftRight(-number2): 
b_int.shiftRight(-number2): 40



Comments and Discussions!

Load comments ↻






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