English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Basic Tutorial

Java flow control

Java array

Java object-oriented (I)

Java object-oriented (II)

Java object-oriented (III)

Java Exception Handling

Java List

Java Queue (queue)

Java Map collection

Java Set collection

Java input/output (I/O)

Java Reader/Writer

Java other topics

Java Math multiplyExact() usage and example

Java Math Mathematical Methods

The Java Math multiyExact() method multiplies the specified numbers and returns the result.

The syntax of the multiplyExact() method is:

Math.multiplyExact(num1, num2)

Note: multiplyExact() is a static method. Therefore, we can access the method Math using the class name.

multipleExact() parameters

  • num1 / num2 - To return the first and second values whose product is to be calculated

Note: The data types of these two values should be int or long.

multipleExact() return value

  • Returnstwo valuesofProduct

Example1: Java mathematical multiplication (Exact)

import java.lang.Math;
class Main {
  public static void main(String[] args) {
    //Create an int variable
    int a = 5;
    int b = 6;
    //multipleExact() with int parameter
    System.out.println(Math.multiplyExact(a, b));  // 30
    // Create a long variable
    long c = 7236L;
    long d = 1721L;
    // multipliExact() with long type parameter
    System.out.println(Math.multiplyExact(c, d));  // 12453156
  }
}

In the above example, we used the Math.multiplyExact() method with int and long variables to calculate the product of each number.

Example2: Math multipleExact() throws an exception

If the multiplication result overflows the data type, the method will throw an exception. That is, the result should be within the range of the specified variable's data type.

import java.lang.Math;
class Main {
  public static void main(String[] args) {
    //Create an int variable.
    //maximum int value
    int a = 2147483647;
    int b = 2;
    //multipleExact() with int parameter
    //Causes an exception
    System.out.println(Math.multiplyExact(a, b));
  }
}

In the above example, the value of a is the maximum int value and the value of b is2When we multiply a and b,

  2147483647 * 2
=> 4294967294    // Out of the range of int type

Therefore, the multiplyExact() method triggers an integer overflow exception.

Recommended Tutorials

Java Math Mathematical Methods