In Java, the BigInteger
class handles calculations with very big integral values that are beyond the limits of the primitive integer type.
The shortValueExact
method of the BigInteger
class converts the value of the BigInteger
to a short
value. An ArithmeticException
is thrown if the value of this BigInteger
is larger than the maximum value a short
type can hold.
public short shortValueExact()
This method doesn’t take any argument.
This method returns the BigInteger
value as a short
value.
The below code demonstrates how to use the shortValueExact
method:
import java.math.BigInteger;class ShortValueExact {public static void main( String args[] ) {BigInteger val1 = new BigInteger("10");BigInteger val2 = new BigInteger("32768");System.out.println("ShortValueExact of " + val1 + " : "+ val1.shortValueExact());try{System.out.println("ShortValueExact of " + val2 + " : "+ val2.shortValueExact());} catch(Exception e) {System.out.println("Exception while converting the " + val2 + " - \n" + e);}}}
Lines 5 to 6: We created two BigInteger
objects, val1
and val2
, with values 10
and 32768
, respectively.
Line 7: We called the shortValueExact
method of the val1
object. This will return the BigInteger
value as short
. The value 10
can be stored in short
, so there will be no exception.
Line 9: We called the shortValueExact
method of the val2
object. The value 32768
is too large to be stored in short
so, an ArithmeticException
is thrown.