Library contents

Java Math.multiplyExact

Multiply two integer quantities while checking whether the result fits.

A simple example

Math.multiplyExact

  1. Start with 2 and 3
  2. Do this Multiply
  3. Result 6
Two groups of three make six. This small product fits exactly.
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        System.out.println(Math.multiplyExact(2, 3));
    }
}
Output
6

Syntax

Java syntax
Math.multiplyExact(packs, units)
JDK 21 method signatures (3)
public static int multiplyExact(int x, int y)
public static long multiplyExact(long x, int y)
public static long multiplyExact(long x, long y)
Run these examples in Java

Save one example at a time as Main.java. Use JDK 21.

java Main.java

Count items in a shipment

A delivery reaches the stockroom while the existing count is still on the books. Before recording the new total, the clerk needs arithmetic that can represent the incoming shipment without silently changing the count.

From the programint packs = 12
Result288
Main.java

class Main {
    public static void main(String[] args) throws Exception {
        int packs = 12;
        int units = 24;
        System.out.println(Math.multiplyExact(packs, units));
    }
}
Output
288

Twelve packs containing 24 items each give 288 items.

Advertisements

Count postcards on a print sheet

A print shop lays out eight rows with six postcards in each row. It calculates how many finished cards a complete sheet produces.

Given8 · 6
Worked result48 items

Using 8 · 6 gives 48 items for this measurement.

Order bulbs for display panels

A gallery uses twelve panels that each take fifteen bulbs. The supply desk calculates the number of bulbs for a full installation.

Given12 · 15
Worked result180 items

Using 12 · 15 gives 180 items for this measurement.

What to watch for

An out-of-range integer result raises ArithmeticException. Decide how the caller should handle that failure.

Documentation for Math.multiplyExact