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.

2147483647

Minimum value of Integer is 232 i.e.

-2147483648

Example

Following is an example to check for Integer Overflow:

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

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.

Java Program to convert decimal to binary
Java Program for Minimum and Maximum values of datatype int
Studyopedia Editorial Staff
[email protected]

We work to create programming tutorials for all.

No Comments

Post A Comment