Java Math.multiplyExact() method in Java
Java has an inbuilt math function called Math.multiplyExact() that returns the sum of the parameters. If the result exceeds an integer, an exception is thrown. There is no need to create an object because multiplyExact(int n1, int n2) is static.
Syntax:
public static int multiplyExact(int n1, int n2)
public static long multiplyExact(long n1, long n2)
public static long multiplyExact(long n1, int n2)
Parameters
It accepts two parameters:
n1=The first parameter
n2=The second parameter
Return
The Math.multiplyExact() method returns the Product of the arguments passed.
Exception
An ArithmeticException will be thrown if one of the parameters is Integer. MAX VALUE, Integer.MIN VALUE, Long.MAX VALUE, or Long.MIN VALUE
Example 1
Filename: MultiplyExactEx1.java
//Program for Math.multiplyExact() method in Java
//importing packages
import java.io.*;
import java.util.*;
public class MultiplyExactEx1
{
public static void main(String[] args)
{
int n1 = 540;
int n2 = 2;
//The input value is integers
// Displays the Product of the two input values(n1*n2)
System.out.println("The Product of two numbers is:"+Math.multiplyExact(n1,n2));
}
}
Output
The Product of two numbers is:1080
Example 2
Filename: MultiplyExactEx2.java
//Program for Math.multiplyExact() method in Java
//importing packages
import java.io.*;
import java.util.*;
public class MultiplyExactEx2
{
public static void main(String[] args)
{
long n1 = Long.MAX_VALUE;
long n2 = 92;
// the input value n1 is overflow
//the output returns the exception
System.out.println(Math.multiplyExact(n1, n2));
}
}
Output
Exception in thread "main" java.lang.ArithmeticException: long overflow
at java.base/java.lang.Math.multiplyExact(Math.java:949)
at MultiplyExactEx2.main(MultiplyExactEx2.java:13)
Example 3
Filename: MultiplyExactEx3.java
//Program for Math.multiplyExact() method in Java
//importing packages
import java.io.*;
import java.util.*;
public class MultiplyExactEx3
{
public static void main(String[] args)
{
int n1 = Integer.MIN_VALUE;
int n2= 303;
// raises an error
System.out.println(Math.multiplyExact(n1, n2));
}
}
Output
Exception in thread "main" java.lang.ArithmeticException: integer overflow
at java.base/java.lang.Math.multiplyExact(Math.java:909)
at MultiplyExactEx3.main(MultiplyExactEx3.java:12)