Write a Java program to Demonstrate the Math.subtractExact() method


This Java program demonstrates the use of the Math.subtractExact() method, which calculates the exact difference between two numbers. The program attempts to subtract 0 and 1 from the minimum integer value, which can cause an integer overflow.

If an integer overflow occurs during the subtraction, the Math.subtractExact() method throws an ArithmeticException. The program catches this exception and prints an error message. Here's what the program does:

  • The main() method initializes an integer variable num to the minimum integer value (Integer.MIN_VALUE).
  • The program attempts to subtract 0 and 1 from num using the Math.subtractExact() method.
  • Since num is the minimum integer value, subtracting 1 from it will result in an integer overflow.
  • The program catches the ArithmeticException thrown by Math.subtractExact() and prints an error message.

Source Code

import java.util.*;
public class Subtract_Exact
{
	public static void main(String[] args)
	{
		int num = Integer.MIN_VALUE;
		try
		{
			System.out.println("Subtraction : " + Math.subtractExact(num, 0));
			System.out.println("Subtraction : " + Math.subtractExact(num, 1));
		}
		catch (Exception e)
		{
			System.out.println("Exception : " + e);
		}
	}
}

Output

Subtraction : -2147483648
Exception : java.lang.ArithmeticException: integer overflow

Example Programs