Library contents

Java Math.toIntExact

Convert a long count to int only when its value is representable.

A simple example

Math.toIntExact

  1. Start with 7 as a long integer
  2. Do this Convert to a narrower integer
  3. Result 7
Seven is in range, so conversion preserves its value.
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        System.out.println(Math.toIntExact(7L));
    }
}
Output
7

Syntax

Java syntax
Math.toIntExact(tickets)
JDK 21 method signatures (1)
public static int toIntExact(long value)
Run these examples in Java

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

java Main.java

Fit a batch count into an integer field

A system must store a batch or grid count in a fixed-width field. Check that the calculation and the final conversion fit before committing the value to the record.

From the programlong tickets = 42000L
Result42000
Main.java

class Main {
    public static void main(String[] args) throws Exception {
        long tickets = 42000L;
        System.out.println(Math.toIntExact(tickets));
    }
}
Output
42000

A batch of 42000 tickets fits in an int.

Advertisements

Transfer a shelf count to a label printer

The warehouse stores inventory totals as 64-bit counts. The printer accepts a signed 32-bit count and this shelf contains 650 items.

Given650
Worked result650

Using 650 gives 650 for this measurement.

Export a class attendance count

An attendance database stores row counts as long integers. The reporting form expects a signed integer and today’s total is 128.

Given128
Worked result128

Using 128 gives 128 for this measurement.

What to watch for

Casting to int can discard high bits. This conversion reports out-of-range values.

Documentation for Math.toIntExact