If you want to perform mathematical operations with large numerical values without overflow, try the BigDecimal class.
Say I want to multiply
200,000,000 * 2,000,000,000,000,000,000 L * 20,000,000
int testValue = 200000000;
System.out.println("After Standard Multiplication = " +
testValue *
2000000000000000000L *
20000000);
The operation value will be -4176287866323730432, which is incorrect.
Using the BigDecimal class, you can exclude the discarded bits and get the correct result.
int testValue = 200000000;
System.out.println("After BigDecimal Multiplication = " +
decimalValue.multiply(
BigDecimal.valueOf(2000000000000000000L).multiply(
BigDecimal.valueOf(testValue))));
After using BigDecimal, multiplication returns the correct result, which
80000000000000000000000000000000000
source
share