Search code examples
javalimitbigintegerbigdecimalnumberformatexception

What are the limits of BigDecimal and BigInteger?


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


Solution

  • 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.