1.

Check for Overflow in Java

Answer»

When a value is assigned to a variable that is more than the MAXIMUM allowed value for that variable, then overflow occurs. There is no exception thrown by the JVM if an overflow occurs and it is the RESPONSIBILITY of the programmer to handle the overflow condition.

A program that checks for overflow in JAVA is given as follows:

public class Demo {   public static void main(String[] args)   {      int num1 = 2147483647;      int num2 = 1;      System.out.println("Number 1: " + num1);      System.out.println("Number 2: " + num2);      long sum = (long)num1 + (long)num2;      if (sum > Integer.MAX_VALUE)      {         throw new ArithmeticException("Overflow occurred!");      }      System.out.println("The sum of TWO numbers is: " + (int)sum);   } }

The OUTPUT of the above program is as follows:

Number 1: 2147483647 Number 2: 1 Exception in thread "main" java.lang.ArithmeticException: Overflow occurred! at Demo.main(Demo.java:14)


Discussion

No Comment Found