Library contents

Java Math.subtractExact

Subtract one integer count from another and detect overflow.

A simple example

Math.subtractExact

  1. Start with 5 and 2
  2. Do this Subtract the second number
  3. Result 3
Removing two units from five leaves three, within the integer range.
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        System.out.println(Math.subtractExact(5, 2));
    }
}
Output
3

Syntax

Java syntax
Math.subtractExact(stock, sold)
JDK 21 method signatures (2)
public static int subtractExact(int x, int y)
public static long subtractExact(long x, long y)
Run these examples in Java

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

java Main.java

Subtract completed sales from stock

A stock ledger changes as units are sold or an adjustment is reversed. Follow the sign of the operation carefully so the remaining inventory reflects the actual movement of goods.

From the programint stock = 90
Result78
Main.java

class Main {
    public static void main(String[] args) throws Exception {
        int stock = 90;
        int sold = 12;
        System.out.println(Math.subtractExact(stock, sold));
    }
}
Output
78

Selling twelve of ninety items leaves 78. A negative result can still be valid arithmetic.

Advertisements

Release a school order

A store holds 84 notebooks for the next term. It hands 36 to one class and records what remains.

Given84 · 36
Worked result48 items

Using 84 · 36 gives 48 items for this measurement.

Subtract damaged tiles

A studio receives 62 tiles and rejects five with cracked edges. The stock card records the usable count.

Given62 · 5
Worked result57 items

Using 62 · 5 gives 57 items for this measurement.

What to watch for

Check the business rule for negative inventory separately from the overflow check.

Documentation for Math.subtractExact