78

I was testing boundary conditions on some code involving a BigDecimal, and I noticed that when a BigDecimal is initialized with the String "1e2147483647" it behaves unexpectedly. It seems to have a value between 0 and 1e-2147483647. When I try calling intValue(), I get a NegativeArraySizeException. I should note that 2147483647 is the max value of an integer on my system. Am I doing something wrong, or is this a problem with BigDecimal?

BigDecimal test = new BigDecimal("1e2147483647");

test.compareTo(new BigDecimal(0));  //Returns 1
test.compareTo(new BigDecimal("1e-2147483647"));  //Returns -1
test.intValue();  //Throws NegativeArraySizeException
4
  • stackoverflow.com/questions/17945985/… Commented Jul 1, 2015 at 19:58
  • Thanks, I hadn't seen that question. I was just surprised it didn't throw a NumberFormatException from the constructor like it does for a number one digit larger. Commented Jul 1, 2015 at 20:02
  • This is more a suggestion than knowing, but 1e-2147483647 is a pretty large number. To be precise, log_2(10^2147483647) / 8 / 1024^3 = 0.83... should yield the minimal size (in Gigabytes) to represent such a large number as integer. Maybe this is some kind of memory allocatin problem? Commented Jul 1, 2015 at 20:03
  • 3
    @DJMatch3000: No, your input is valid and representable, though that's the maximum exponent you can represent for BigDecimal. Your bug is legit. Commented Jul 1, 2015 at 20:05

1 Answer 1

87

No, you appear to have a legit bug. The bug presents in JDK7 but fixed in JDK8. Your values are correctly representable as BigDecimals, and should behave correctly, but don't.

Tracing through the source code of BigDecimal, on line 2585, this.precision() is 1, and this.scale is -2147483647. this.precision() - this.scale therefore overflows, and the following overflow is not handled correctly.

This bug has been fixed in JDK8 by doing the subtraction in long arithmetic.

Sign up to request clarification or add additional context in comments.

1 Comment

Does this in Android 17's Java (similar to JDK6)?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.