In this Example we are going to understand the exceptions when we are adding the integer with max range of int.
Error Message :
Exception in thread "main" java.lang.ArithmeticException: integer overflow
at java.base/java.lang.Math.addExact(Math.java:825)
at MathTest.main(MathTest.java:7)
Error Description :
public class MathTest {
public static void main(String[] args) {
int x = 2147483647;
int y = 32767;
int res = Math.addExact(x, y);//java.math.addExact(int a, int b);
System.out.println(res);
}
}
In the above example ,the red background color line is giving the exception.
The x value is more than the int size so we are getting the Integer over flow error.
Solution:
To avoid this exception we need to capture in catch block and doing the addition using bigInteger with same int values.
import java.math.BigInteger;
public class MathTest {
public static void main(String[] args) {
int x = 2147483647;
int y = 32767;
try {
float res = Math.addExact(x, y);//java.math.addExact(int a, int b);
System.out.println(res);
}catch(ArithmeticException e) {
BigInteger b1 = BigInteger.valueOf(x);
BigInteger b2 = BigInteger.valueOf(y);
BigInteger res1 = b1.add(b2);
System.out.println(res1);
}
}
}
Output:
2147516414
Post a comment
Please share your valuable feedback and share this article in social media.