Java BigDecimal Error Possible Overflow Error

I tested the boundary conditions for some code using BigDecimal , and I noticed that when a BigDecimal initialized to String "1e2147483647" , it behaves unexpectedly. It seems to have a value between 0 and 1e-2147483647 . When I try to call intValue() , I get a NegativeArraySizeException . I should note that 2147483647 is the maximum integer value in 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 
+79
java bigdecimal
Jul 01 '15 at 19:53
source share
1 answer

No, you seem to have a legitimate mistake. The error is present in JDK7, but fixed in JDK8. Your values ​​are correctly represented as BigDecimal s and should behave correctly, but not.

Tracking through the BigDecimal source code , on line 2585, this.precision() is 1, and this.scale is -2147483647 . this.precision() - this.scale therefore overflows, and the next overflow does not handle correctly.

This bug was fixed in JDK8 by performing subtraction in long arithmetic .

+87
Jul 01 '15 at 19:56
source share



All Articles