Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

intvalueexact
biginteger
java
communitycreator

What is the BigInteger.intValueExact() method in Java?

Programming Bytes

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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.

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);
}
}
}
Using the "BigInteger" method

Explanation

In the above code, we do the following:

  • Lines 5-6: We create two BigIntegerobjects: 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.

RELATED TAGS

intvalueexact
biginteger
java
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring