Sometimes we need
to handle integer numbers larger than Long.MAX_VALUE or
floating-point values larger than Double.MAX_VALUE. Use the
BigInteger or BigDecimal values available in package java.math to
handle large values.
Java Overflow
In arithmetic operations when using int or long, if the value becomes too large, Java saves only the low order 32 bits for int and 64 bits for longs and thus returning incorrect result. In Java this is known as Overflow. Arithmetic operators neither report overflow nor do they throw any runtime exception. See example given below for better understanding of Java Overflow.
public class JavaOverflow { public static void main(String[] args) { int number = 2000000000; // Close to int max value. System.out.println("number = " + number); System.out.println("number + 1 = " + (number + 1)); System.out.println("number * 3 = " + (number * 3)); System.out.println("number * 4 = " + (number * 4)); } }
Output showing
Overflow when Integer max limit is achieved
number =
2000000000
number + 1 =
2000000001
number * 3 =
1705032704 // Smaller
number * 4 =
-589934592 // Negative
Solution to Java
Overflow
java.math package
provides BigInteger and BigDecimal values to handle Java Overflow.
Both BigInteger and BigDecimal objects are immutable.
In above example
if we use BigInteger instead of integer we get correct result.
public class JavaOverflow { public static void main(String[] args) { BigInteger number = BigInteger.valueOf(2000000000); System.out.println("number = " + number); System.out.println("number + 1= " + number.add(BigInteger.ONE)); System.out.println("number * 3 = " + number.multiply(BigInteger.valueOf(3))); System.out.println("number * 4 = " + number.multiply(BigInteger.valueOf(4))); } }
Output showing
correct result
number =
2000000000
number + 1=
2000000001
number * 3 =
6000000000
number * 4 =
8000000000