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


This Java program demonstrates how to use the Math.multiplyExact() method to multiply two integers and handle the potential overflow scenario. Here's a step-by-step explanation of how the program works:

  • The java.util.Scanner class is imported to enable input from the user.
  • The public class Multiply_Exact line declares a new public class named Multiply_Exact.
  • The public static void main(String[] args) method is the entry point for the program. It takes an array of strings as input and returns nothing.
  • An integer variable num is declared and initialized to the minimum value of an int.
  • The System.out.println() method is used to display the product of two integers (12 and 25) using the Math.multiplyExact() method. Since the product of 12 and 25 does not cause an overflow, this call to Math.multiplyExact() will return a valid result.
  • The System.out.println() method is used to display the product of num and 3 using the Math.multiplyExact() method. Since the product of num and 3 will cause an overflow, this call to Math.multiplyExact() will throw an exception.
  • A try-catch block is used to catch the exception thrown by the second call to Math.multiplyExact() and handle it gracefully. The catch block displays an error message that includes the exception details.

Source Code

import java.util.*;
public class Multiply_Exact
{
	public static void main(String[] args)
	{
		int num = Integer.MIN_VALUE;
		try
		{
			System.out.println("Product : " + Math.multiplyExact(12, 25));
			System.out.println("Product : " + Math.multiplyExact(num, 3));
		} catch (Exception e)
		{
			System.out.println("Exception : " + e);
		}
	}
}

Output

Product : 300
Exception : java.lang.ArithmeticException: integer overflow

Example Programs