Java .multiplyExact()
Published Dec 14, 2022
Contribute to Docs
The .multiplyExact() method returns the product of its arguments.
Syntax
Math.multiplyExact(x, y)
The .multiplyExact() method takes two parameters: x and y (a multiplicand and multiplier). Both parameters must be of either type int or long.
The .multiplyExact() method returns the result of x multiplied by y.
An exception is thrown if the result exceeds type int or long or is equal to:
Integer.MAX_VALUEInteger.MIN_VALUELong.MAX_VALUELong.MIN_VALUE
Example
In the following example, the .multiplyExact() method first returns the product of two numbers and then throws an exception:
// Main.javapublic class Main {public static void main(String[] args) {int num1 = 8;int num2 = 2;/*Returns the product of the two numbers*/System.out.println(num1 + " multiplied by " + num2 + " equals to " + Math.multiplyExact(num1, num2));long c = 299792458;long m = Long.MAX_VALUE;/*Overflow will occur if any one of the arguments isLong.MAX_VALUE or Integer.MAX_VALUE.*/System.out.println(Math.multiplyExact(c, m));}}
This will produce the following output:
8 multiplied by 2 equals to 16Exception in thread "main" java.lang.ArithmeticException: long overflowat java.base/java.lang.Math.multiplyExact(Math.java:946)at Main.main(Main.java:17)
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Java on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Learn to code in Java — a robust programming language used to create software, web and mobile apps, and more.
- Beginner Friendly.17 hours