The multiplyExact() method of Math class returns the product of the argument, throwing an exception if the result overflows an int or a long.
Syntax:
- public static int multiplyExact (int x, int y)
- public static long multiplyExact (long x, int y)
- public static long multiplyExact (long x, long y)
Parameters:
The parameters ‘x’ and ‘y’ represent the first and second value.
Return Value:
The multiplyExact () method returns the product of the arguments x and y.
Throws:
The multiplyExact () method throws:
ArithmeticException- if the result overflows an int or long.
Example 1:
1 2 3 4 5 6 7 8 9 10 11 |
public class JavaMathMultiplyExactExample1 { public static void main(String[] args) { int a = 60; int b= 6; //returns the product of a and b System.out.println("Product of "+a+" and "+ b+ " is : "+Math.multiplyExact(a,b)); } } |
Output:
1 2 3 |
Product of 60 and 6 is : 360 |
Example 2:
1 2 3 4 5 6 7 8 9 10 11 |
public class JavaMathMultiplyExactExample2 { public static void main(String[] args) { long a = 0; int b= 6; //returns zero if either argument is zero System.out.println("Product of "+a+" and "+ b+ " is : "+Math.multiplyExact(a,b)); } } |
Output:
1 2 3 |
Product of 0 and 6 is : 0 |
Example 3:
1 2 3 4 5 6 7 8 9 10 11 |
public class JavaMathMultiplyExactExample3 { public static void main(String[] args) { long a = 0l/0l; long b= 1; //returns an exception is the either argument is NaN System.out.println("Product of "+a+" and "+ b+ " is : "+Math.multiplyExact(a,b)); } } |
Output:
1 2 3 4 5 |
Exception in thread "main" java.lang.ArithmeticException: / by zero at com.TutorialsAndExample.JavaMathMultiplyExactExample3.main (JavaMathMultiplyExactExample3.java:5) |
Example 4:
1 2 3 4 5 6 7 8 9 10 11 |
public class JavaMathMultiplyExactExample4 { public static void main(String[] args) { long a = Long.MAX_VALUE; long b= Long.MIN_VALUE; // throws ArithmeticException, if the result overflows a long. System.out.println("Product of "+a+" and "+ b+ " is : "+Math.multiplyExact(a,b)); } } |
Output:
1 2 3 4 5 6 |
Exception in thread "main" java.lang.ArithmeticException: long overflow at java.lang.Math.multiplyExact(Math.java:892) at com.Tutorial1AndExamples.JavaMathMultiplyExactExample4.main (JavaMathMultiplyExactExample4.java:8) |