1.

Check for underflow in Java

Answer»

When a value is assigned to a variable that is less than the minimum allowed value for that variable, then underflow occurs. There is no exception THROWN by the JVM if an underflow occurs and it is the responsibility of the programmer to HANDLE the underflow condition.

A program that checks for underflow in Java is given as follows:

public class Demo {   public static void main(String[] ARGS)   {      int num1 = -2147483648;      int num2 = -1;      System.out.println("Number 1: " + num1);      System.out.println("Number 2: " + num2);      long sum = (long)num1 + (long)num2;      if (sum < Integer.MIN_VALUE)      {         throw new ArithmeticException("Underflow occurred!");      }      System.out.println("The sum of two numbers is: " + (int)sum);   } }

The output of the above program is as follows:

Number 1: -2147483648 Number 2: -1 Exception in thread "main" java.lang.ArithmeticException: Underflow occurred! at Demo.main(Demo.java:15)


Discussion

No Comment Found