Java Math.divideExact
Divide integers with truncation toward zero and detect signed overflow.
A simple example
Math.divideExact
- Start with 7 and 3
- Do this Divide as integers
- Result 2
class Main {
public static void main(String[] args) throws Exception {
System.out.println(Math.divideExact(7, 3));
}
}
2
Syntax
Math.divideExact(credits, players)
JDK 21 method signatures (2)
public static int divideExact(int x, int y)
public static long divideExact(long x, long y)Run these examples in Java
Save one example at a time as Main.java. Use JDK 21.
java Main.javaDivide reward credits into whole shares
A rewards desk splits credits into whole shares. Work with signed totals carefully because division near zero can produce a different result under different integer rounding rules.
class Main {
public static void main(String[] args) throws Exception {
int credits = 17;
int players = 4;
System.out.println(Math.divideExact(credits, players));
}
}
4
Each of four players receives four whole credits. The remainder can be assigned separately.
Make complete paint sets
A studio has 29 paint tubes and puts six in each set. It lists only sets that can be handed out complete.
Four sets use 24 tubes. Five tubes stay on the shelf.
Share a complete batch of tickets
Forty tickets are shared equally among eight activity groups. The organizer records the whole-number share per group.
Every ticket is allocated because the division has zero remainder.
What to watch for
Despite its name, this method allows a remainder. Zero divisors and the minimum value divided by minus one raise an exception.