Java Math.toIntExact
Convert a long count to int only when its value is representable.
A simple example
Math.toIntExact
- Start with 7 as a long integer
- Do this Convert to a narrower integer
- Result 7
class Main {
public static void main(String[] args) throws Exception {
System.out.println(Math.toIntExact(7L));
}
}
7
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.javaFit 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.
class Main {
public static void main(String[] args) throws Exception {
long tickets = 42000L;
System.out.println(Math.toIntExact(tickets));
}
}
42000
A batch of 42000 tickets fits in an int.
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.
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.
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.