Library contents

Java Math.decrementExact

Subtract one from a counter and detect overflow at the lower limit.

A simple example

Math.decrementExact

  1. Start with 3
  2. Do this Subtract 1
  3. Result 2
The checked decrement moves one integer closer to zero.
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        System.out.println(Math.decrementExact(3));
    }
}
Output
2

Syntax

Java syntax
Math.decrementExact(places)
JDK 21 method signatures (2)
public static int decrementExact(int a)
public static long decrementExact(long a)
Run these examples in Java

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

java Main.java

Reserve one available place

A desk issues numbered places one at a time. Check the next or remaining count at the edge of its allowed range so a full counter cannot wrap into an apparently valid booking.

From the programint places = 12
Result11
Main.java

class Main {
    public static void main(String[] args) throws Exception {
        int places = 12;
        System.out.println(Math.decrementExact(places));
    }
}
Output
11

Taking one of twelve places leaves eleven.

Advertisements

Release one museum headset

The desk has seven headsets available at opening. It hands one to a visitor and updates the count.

Given7
Worked result6

Using 7 gives 6 for this measurement.

Use the final appointment slot

A clinic calendar has one slot left today. A booking consumes that slot and the calendar updates availability.

Given1
Worked result0

Using 1 gives 0 for this measurement.

What to watch for

Zero can become minus one without arithmetic overflow. Validate availability before reserving.

Documentation for Math.decrementExact