18 Aug Java Program to check for Integer Overflow
Checking for Integer Overflow means adding a value to the maximum value. For Integer, we will increment by 1 to the Integer.MAX_VALUE. On incrementing, an error won’t be visible. However, the output will be Integer.MIN_VALUE.
Maximum value of Integer is 231 – 1 i.e.
1 2 3 |
2147483647 |
Minimum value of Integer is 232 i.e.
1 2 3 |
-2147483648 |
Example
Following is an example to check for Integer Overflow:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
public class Example { public static void main(String[] args) { int a = Integer.MAX_VALUE; System.out.println("Maximum value of Integer = "+a); // incrementing Maximum value of Integer int i = a + 1; System.out.println("Incrementing Maximum value of Integer = "+i); long k = (long)i; if (k > a) { throw new ArithmeticException("Integer Overflow!"); } } } |
Output
1 2 3 4 |
Maximum value of Integer = 2147483647 Incrementing Maximum value of Integer = -2147483648 |
On incrementing MAX_VALUE, it results in MIN_VALUE for Integer type in Java as shown above. Java handles overflow accordingly for Integer type.
No Comments