What are the limits of BigDecimal and BigInteger?

2019-03-01 13:12发布

问题:

This question already has an answer here:

  • Is there an upper bound to BigInteger? [duplicate] 3 answers
  • What does BigInteger having no limit mean? 4 answers

I was multiplying very two huge BigIntegervalues in a program. It failed. What are the limits of BigInteger and BigDecimal ?

回答1:

You won't get NumberFormatException multiplying large numbers. If the number produced is too large, you will get a cryptic NegativeArraySizeException as the size of the array overflows.

You are more likely to get an out of memory error.

The limit is 32 * 2^32-1 bits for BigInteger or about 2^(4 billion).

You can get a NumberFormatException if you

  • create a BigInteger from an empty byte[]
  • use a signum < -1 or > +1
  • try to parse a number in base >36 or < 2
  • have a string with illegal digits.

When you get an exception you should also look at the message and the stack trace as this usually gives you the real cause.



回答2:

there shouldn't be a limit, except for memory, but maybe there is, according to the implementation of the class (for example, some fields there might be int or long).