×

Java Programs

Java Practice

Java program to demonstrate the Math.multiplyExact() method

Java example to demonstrate the Math.multiplyExact() method.
Submitted by Nidhi, on May 17, 2022

Problem statement

In this program, we will create an integer number from the user using the Scanner class. Then we will use Math.multiplyExact() method. The Math.multiplyExact() method returns the product of its arguments, throwing an exception if the result overflows.

Java program to demonstrate the Math.multiplyExact() method

The source code to demonstrate the Math.multiplyExact() method is given below. The given program is compiled and executed successfully.

// Java program to demonstrate the 
// Math.multiplyExact() method

import java.util.*;

public class Main {
  public static void main(String[] args) {
    int num = Integer.MIN_VALUE;

    try {
      System.out.println("Product is: " + Math.multiplyExact(675, 25));
      System.out.println("Product is: " + Math.multiplyExact(num, 2));
    } catch (Exception e) {
      System.out.println("Exception: " + e);
    }
  }
}

Output

Product is: 16875
Exception: java.lang.ArithmeticException: integer overflow

Explanation

In the above program, we imported the "java.util.*" package to use the Scanner class. Here, we created a public class Main that contains a main() method.

The main() method is the entry point for the program. And, created a variable num of integer type and then we used Math.multiplyExact() method. It returns the product of its arguments, throwing an exception if the result overflows.

Java Math Class Programs »



Related Programs



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.