Library contents

Java Math.incrementExact

Add one while checking whether an integer counter has reached its limit.

A simple example

Math.incrementExact

  1. Start with 3
  2. Do this Add 1
  3. Result 4
A checked increment returns the next integer when it fits.
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        System.out.println(Math.incrementExact(3));
    }
}
Output
4

Syntax

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

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

java Main.java

Issue the next numbered ticket

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 ticket = 99
Result100
Main.java

class Main {
    public static void main(String[] args) throws Exception {
        int ticket = 99;
        System.out.println(Math.incrementExact(ticket));
    }
}
Output
100

After ticket 99 the next number is 100.

Advertisements

Issue a coat-check ticket

The last tag used at a school concert was 249. The next guest needs the following consecutive number.

Given249
Worked result250

Using 249 gives 250 for this measurement.

Number the next lab sample

A class has recorded sample 79. A student adds one to assign the next identifier.

Given79
Worked result80

Using 79 gives 80 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.incrementExact