Java multiplyExact() in Math

The java.lang.Math.multiplyExact() is a built-in math function in java which returns the product of the
arguments.It throws an exception if the result overflows an int.As multiplyExact(int a, int b) is static, so
object creation is not required.

Syntax :

public static int multiplyExact(int a, int b)
public static double multiplyExact(int a, double b)
Parameter :
 a : the first value
 b : the second value
Return :
This method returns the product of the arguments.
Exception :
It throws ArithmeticException - if the result overflows an int

Example :To show working of java.lang.Math.multiplyExact() method.

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to demonstrate working
// of java.lang.Math.multiplyExact() method
import java.lang.Math;
  
class Gfg1 {
  
    // driver code
    public static void main(String args[])
    {
        int a = 25, b = 5;
        System.out.println(Math.multiplyExact(a, b));
  
        long c = 100, d = 50;
        System.out.println(Math.multiplyExact(c, d));
    }
}

chevron_right


Output:

125
5000
filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to demonstrate working
// of java.lang.Math.multiplyExact() method
import java.lang.Math;
  
class Gfg2 {
  
    // driver code
    public static void main(String args[])
    {
        int x = Integer.MAX_VALUE;
        int y = 2;
  
        System.out.println(Math.multiplyExact(x, y));
    }
}

chevron_right


Output:

Runtime Error :
Exception in thread "main" java.lang.ArithmeticException: integer overflow
    at java.lang.Math.multiplyExact(Math.java:867)
    at Gfg2.main(File.java:13)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.