Java Math multiplyExact() Method

java math multiplyExact() method

Java Math Class

Here, in the page we will discuss about the math multiplyExact() Method in java.
Java Math class provides several methods to perform several operations on math calculations like max(), min(), sin(), cos(), round(), ceil(), floor(), abs() etc. The java.lang.Math class contains various methods for performing basic numeric operations

Java Math multiplyExact() Method :

Java’s Math.multiplyExact() method is a utility method in the Math class that performs an arithmetic operation to multiply two integers and return the result, throwing an exception if the result overflows the range of the int data type.
 
The multiplyExact() method takes two parameters, both of which must be int values. It returns an int value representing the result of the multiplication.
 
If the result of the multiplication overflows the range of the int data type, the multiplyExact() method throws an ArithmeticException.
 
Note: The data type of both values should be either int or long.

Syntax  :

public static int multiplyExact(int x, int y)
public static double multiplyExact(long x, long y)

Example 1 :  

Run
public class Main {
    public static void main(String[] args) {
        // Multiply two int values
        int x = 100;
        int y = 200;
        int result1 = Math.multiplyExact(x, y);
        System.out.println(result1); // prints 20000

        // Multiply two long values
        long a = 1000000000L;
        long b = 2000000000L;
        long result2 = Math.multiplyExact(a, b);
        System.out.println(result2); // prints 2000000000000
    }
}

Output :

20000
2000000000000

Example 2:  

Run
public class Main {
    public static void main(String[] args) {
        // Multiply two int values that will cause an overflow
        int x = Integer.MAX_VALUE;
        int y = 2;
        try {
            int result = Math.multiplyExact(x, y);
            System.out.println(result);
        } catch (ArithmeticException e) {
            System.out.println("Overflow occurred");
        }
    }
}

Output :

Overflow occurred

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription