Java Math.floorDivExact
Divide two signed integers and round the quotient down while checking for overflow.
A simple example
Math.floorDivExact
- Start with −7 divided by 3
- Do this Round the quotient down
- Result −3
class Main {
public static void main(String[] args) throws Exception {
System.out.println(Math.floorDivExact(-7, 3));
}
}
-3
Syntax
Math.floorDivExact(shift, period)
JDK 21 method signatures (2)
public static int floorDivExact(int x, int y)
public static long floorDivExact(long x, long y)Run these examples in Java
Save one example at a time as Main.java. Use JDK 21.
java Main.javaFind a time slot before a schedule starts
A shift planner numbers intervals relative to opening time. Assign a time before opening to the correct earlier slot rather than losing the sign at the boundary.
class Main {
public static void main(String[] args) throws Exception {
int shift = -7;
int period = 3;
System.out.println(Math.floorDivExact(shift, period));
}
}
-3
An event seven minutes before the start falls in slot minus three when slots are three minutes wide.
Locate an event before opening
A desk groups arrivals into ten-minute blocks, with block zero beginning at opening time. A volunteer arrived one minute before opening and needs the correct block label.
Floor division assigns the minute immediately before zero to block minus one.
Group an afternoon reading
A meter logs one entry per five-minute block starting at noon. A reading comes in seventeen minutes after noon.
Block three covers minutes fifteen through nineteen.
What to watch for
A zero divisor and the minimum signed value divided by minus one raise ArithmeticException.