ryvantage
ryvantage

Reputation: 13496

BigInteger::intValueExact() - what's the point?

I noticed that the class BigInteger received a new method in Java 8: intValueExact().

My question is: why?

BigInteger bigInt = ... ;

bigInt.intValueExact();

BigInteger already had intValue(). The intValueExact() is meant to throw an error when your BigInteger does not hold an exact int value, but my question is: how could it be possible to give a BigInteger a value that will not equate to an exact int ? Can someone provide an example of when this method would throw an ArithmeticException ??

Upvotes: 10

Views: 8495

Answers (3)

BitNinja
BitNinja

Reputation: 1487

From the doc:

Converts this BigInteger to an int, checking for lost information. If the value of this BigInteger is out of the range of the int type, then an ArithmeticException is thrown.

So quite simply if the value of the BigInteger is greater than 2^31 - 1 then an ArithmeticException is thrown.

Upvotes: 1

user2357112
user2357112

Reputation: 281604

new BigInteger("10000000000000000000000000000000000000000000000").intValueExact()

If the BigInteger is too big an integer to fit into an int, the exception is thrown.

Upvotes: 13

rgettman
rgettman

Reputation: 178303

The intValue() method will only keep the lowest 32 bits that will fit in an int, discarding information if necessary.

Converts this BigInteger to an int. This conversion is analogous to a narrowing primitive conversion from long to int as defined in section 5.1.3 of The Java™ Language Specification: if this BigInteger is too big to fit in an int, only the low-order 32 bits are returned. Note that this conversion can lose information about the overall magnitude of the BigInteger value as well as return a result with the opposite sign.

The intValueExact() method will throw an exception in this case rather than give you a different value.

Converts this BigInteger to an int, checking for lost information. If the value of this BigInteger is out of the range of the int type, then an ArithmeticException is thrown.

Upvotes: 15

Related Questions