Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
Java Program to check for Integer overflow
To check for Integer overflow, we need to check the Integer.MAX_VALUE, which is the maximum value of an integer in Java.
Let us see an example wherein integers are added and if the sum is more than the Integer.MAX_VALUE, then an exception is thrown.
Example
public class Demo {
public static void main(String[] args) {
int val1 = 9898989;
int val2 = 6789054;
System.out.println("Value1: "+val1);
System.out.println("Value2: "+val2);
long sum = (long)val1 + (long)val2;
if (sum > Integer.MAX_VALUE) {
throw new ArithmeticException("Overflow!");
}
// displaying sum
System.out.println("Sum: "+(int)sum);
}
}
Output
Value1: 9898989 Value2: 6789054 Sum: 16688043
In the above example, we have taken the following two integers −
int val1 = 9898989; int val2 = 6789054;
Now we will cast and add them to a long.
long sum = (long)val1 + (long)val2;
If the result is more than the maximum value, then a exception is thrown.
if (sum > Integer.MAX_VALUE) {
throw new ArithmeticException("Overflow!");
} Advertisements
