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

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

My question is why?

BigInteger bigInt = ... ;

bigInt.intValueExact();

BigIntegeralready had intValue(). intValueExact()designed to throw an error when yours BigIntegerdoes not have an exact value int, but my question is: how could one give a value BigIntegerthat would not correspond to the exact one int? Can someone provide an example of when this method will call ArithmeticException??

+4
source share
3 answers
new BigInteger("10000000000000000000000000000000000000000000000").intValueExact()

If the value is BigIntegertoo large for the integer that fits in int, an exception will be thrown.

+9
source

intValue() 32 , int, .

BigInteger int. long int, 5.1.3 Java ™: BigInteger , int, 32 . , BigInteger, .

intValueExact() , .

BigInteger int, . BigInteger int, ArithmeticException.

+9

From doc :

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

So simple, if the value is BigIntegergreater than 2 ^ 31 - 1, it is thrown ArithmeticException.

+1
source

Source: https://habr.com/ru/post/1546203/


All Articles