The
BigInteger
class 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
.
public int intValueExact()
This method doesn’t take any arguments.
This method returns the BigInteger
value as an int
value.
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);}}}
In the above code, we do the following:
BigInteger
objects: val1
with value 10
, and val2
with the value 2147483648
.Line 7: We call the intValueExact
method of the val1
object. This returns the BigInteger
value as int
. The value 10
can be stored in int
, so there is no exception.
Line 9: We call the intValueExact
method of the val2
object. The value 2147483648
is too large to be stored in int
, so an ArithmeticException
is thrown.