What is the BigInteger.intValueExact() method in Java?
The
BigIntegerclass in Java handles calculations with big integral values that are beyond the limits of the primitive integer type.
The intValueExact() method of the BigInteger class converts the value of the BigInteger to an int value. If the value of this BigInteger is larger than the maximum value of an int type, it throws an ArithmeticException.
Syntax
public int intValueExact()
Parameter
This method doesn’t take any arguments.
Return value
This method returns the BigInteger value as an int value.
Code
The code below demonstrates how to use the intValueExact method.
import java.math.BigInteger;class IntValueExact {public static void main( String args[] ) {BigInteger val1 = new BigInteger("10");BigInteger val2 = new BigInteger("2147483648");System.out.println("IntValueExact of " + val1 + " : "+ val1.intValueExact());try{System.out.println("IntValueExact of " + val2 + " : "+ val2.intValueExact());} catch(Exception e) {System.out.println("Exception while converting the " + val2 + " - \n" + e);}}}
Explanation
In the above code, we do the following:
- Lines 5-6: We create two
BigIntegerobjects:val1with value10, andval2with the value2147483648.
-
Line 7: We call the
intValueExactmethod of theval1object. This returns theBigIntegervalue asint. The value10can be stored inint, so there is no exception. -
Line 9: We call the
intValueExactmethod of theval2object. The value2147483648is too large to be stored inint, so anArithmeticExceptionis thrown.