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
??
BigInteger provides analogues to all of Java's primitive integer operators, and all relevant methods from java. lang. Math. Additionally, BigInteger provides operations for modular arithmetic, GCD calculation, primality testing, prime generation, bit manipulation, and a few other miscellaneous operations.
intValue() converts this BigInteger to an int. This conversion is analogous to a narrowing primitive conversion from long to int. If this BigInteger is too big to fit in an int, only the low-order 32 bits are returned.
Now that we are able to represent numerical numbers using Strings, we have raised the maximum number we can initialize a big integer to a number with 2147483647 digits. This is because the maximum length of a String is Integer. MAX_VALUE.
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.
new BigInteger("10000000000000000000000000000000000000000000000").intValueExact()
If the BigInteger
is too big an integer to fit into an int
, the exception is thrown.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With