What is Math.multiplyHigh in Java?

Overview

multiplyHigh is a static method in Java’s Math class that returns as a long, the most significant 64 bits of the producteach value is 64 bits, so the product is 128 bits of two long values.

This method was introduced in Java 9. Use Java versions 9 and above to utilize this method.

This method is annotated with HotSpotIntrinsicCandidate.

Note: The @HotSpotIntrinsicCandidate annotation is specific to the HotSpot Virtual Machine. It indicates that an annotated method may be (but is not guaranteed to be) intensified by the HotSpot VM. A method is intensified if the HotSpot VM replaces the annotated method with hand-written assembly and/or hand-written compiler IRa compiler intrinsic to improve performance.

Method signature

public static long multiplyHigh(long x, long y)

Parameters:

  • long x: The first long value to be multiplied
  • long y: The second long value to be multiplied

Returns:

The method returns a 64-bit long value that is the product of the two long values.

Examples

In the code below, we define two long values and a long result variable to hold the result of the product.

import java.lang.Math;
public class Main {
public static void main(String[] args) {
long firstValue = 1234567654;
long secondValue = 654334543;
long result = Math.multiplyHigh(firstValue, secondValue);
System.out.println("Result - " + result);
}
}

In the code below, we use the maximum value and minimum value a long datatype can hold as the values to be multiplied.

import java.lang.Math;
public class Main {
public static void main(String[] args) {
long firstValue = Long.MAX_VALUE;
long secondValue = Long.MIN_VALUE;
long result = Math.multiplyHigh(firstValue, secondValue);
System.out.println("Result - " + result);
}
}