What is BigInteger.shortValueExact() method in Java?
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.
Syntax
public short shortValueExact()
This method doesn’t take any argument.
This method returns the BigInteger value as a short value.
Example
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);}}}
Explanation
-
Lines 5 to 6: We created two
BigIntegerobjects,val1andval2, with values10and32768, respectively. -
Line 7: We called the
shortValueExactmethod of theval1object. This will return theBigIntegervalue asshort. The value10can be stored inshort, so there will be no exception. -
Line 9: We called the
shortValueExactmethod of theval2object. The value32768is too large to be stored inshortso, anArithmeticExceptionis thrown.