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:
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); } } }
Subtraction : -2147483648 Exception : java.lang.ArithmeticException: integer overflow
Learn All in Tamil © Designed & Developed By Tutor Joes | Privacy Policy | Terms & Conditions