Subtract Integers and Check for Overflow in Java



In this article, we will subtract two integers and check if the result causes an overflow in Java. To check for Integer overflow, we need to check the Integer.MAX_VALUE with the subtracted integers result, Here, Integer.MAX_VALUE is the maximum value of an integer in Java. Let us see an example wherein integers are subtracted and if the result is more than Integer.MAX_VALUE, then an exception is thrown.

Problem Statement

Write a program in Java to subtract integers and check for overflow ?

Input

val1 = 9898999
val2 = 8784556

Output

Value1: 9898999
Value2: 8784556
Subtraction Result: 1114443

Steps to subtract integers and check for overflow

Following are the steps to subtract integers and check for overflow ?

  • Declare two integer variables, val1 and val2, and assign values to them.
  • Print the values of val1 and val2.
  • Cast both integers to long and perform the subtraction to store the result in the variable sub.
  • Check if sub is greater than Integer.MAX_VALUE.
  • If the condition is true, throw an ArithmeticException with the message "Overflow!".
  • If no exception is thrown, print the subtraction result cast back to an integer.

Java program to subtract integers and check for overflow

The following is an example showing how to check for Integer overflow ?

public class Demo {
   public static void main(String[] args) {
      int val1 = 9898999;
      int val2 = 8784556;
      System.out.println("Value1: "+val1);
      System.out.println("Value2: "+val2);
      long sub = (long)val1 - (long)val2;
      if (sub > Integer.MAX_VALUE) {
         throw new ArithmeticException("Overflow!");
      }
      // displaying subtraction result
      System.out.println("Subtraction Result: "+(int)sub);
   }
}

Output

Value1: 9898999
Value2: 8784556
Subtraction Result: 1114443

Code Explanation

The program initializes two integers, val1 and val2, and prints their values. Both integers are cast to long before subtraction to avoid overflow during the operation. The result of the subtraction is stored in sub. The program then checks if sub exceeds Integer.MAX_VALUE, and if it does, it throws an ArithmeticException. If not, it prints the result of the subtraction, cast back to an integer.

Updated on: 2024-10-10T11:38:29+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements