1

In a method I remember there was an error thrown at a line having the following code.

java.lang.ClassCastException: java.math.BigDecimal cannot be cast to java.lang.Integer

at

Integer count = (Integer) result[1];

and I replaced the code to

Integer count = ((BigDecimal) result[1]).intValue();

the error has gone.

But some how I got the following error for the same code snippets in the new project.

java.lang.ClassCastException: java.math.BigDecimal incompatible with java.lang.Integer

Just wanted to know, both of these are the same or not.

Nidheesh
  • 4,390
  • 29
  • 87
  • 150

3 Answers3

0

Both are not same Integer count = (Integer) result[1]; tries to cast the BigDecimal Object to the Integer. Will thorw an exception always.

Integer count = ((BigDecimal) result[1]).intValue(); this will work if your result has BigDecimal Object.

Better you check you have compiled your code properly.

0

Try this:

Integer count = ((BigDecimal) result[1]).intValueExact();

Or: http://www.tutorialspoint.com/java/math/bigdecimal_intvalueexact.htm

Simego
  • 431
  • 5
  • 16
0

BigDecimal.intValueExact() (or BigDecimal.intValue()) :

Converts this BigDecimal to an int. This conversion is analogous to a narrowing primitive conversion from double to short as defined in the Java Language Specification: any fractional part of this BigDecimal will be discarded, and if the resulting "BigInteger" is too big to fit in an int, only the low-order 32 bits are returned. Note that this conversion can lose information about the overall magnitude and precision of this BigDecimal value as well as return a result with the opposite sign.

Plase take into consideration that BigDecimal may contain values which are larger than Integer.MAX_VALUE.

Reference: here

Community
  • 1
  • 1
Sandeep
  • 712
  • 1
  • 10
  • 22