Java integer division truncates toward zero, while Math.floorDiv rounds toward negative infinity and floorMod uses the corresponding nonnegative remainder for a positive divisor.
Java floorDiv and floorMod: assign negative coordinates to stable buckets
Choose the bucket rule
A coordinate of -7 with bucket width 3 belongs in bucket -3 when buckets cover [-9,-6), [-6,-3), and so on. Plain -7 / 3 yields -2; floorDiv yields -3, and floorMod supplies offset 2 inside that bucket. The quotient and remainder must come from the same convention.
Operator rules explain truncating division. The fixture prints both conventions so an index mapping can be checked before it reaches a data structure.
Guard the divisor
A zero width throws ArithmeticException. A negative divisor changes the sign policy for the remainder, so this bucket contract requires a positive width. Also consider the MIN_VALUE divided by -1 overflow case for unrestricted signed inputs.
Working program
public class WarehouseGridBucket {
public static void main(String[] args) {
int coordinate = -7;
int width = 3;
System.out.println("truncated=" + coordinate / width + ":" + coordinate % width);
System.out.println("floored=" + Math.floorDiv(coordinate, width) + ":" + Math.floorMod(coordinate, width));
}
}Output
truncated=-2:-1
floored=-3:2Cost and ownership
Both mappings use constant work and storage. The choice affects key distribution and lookup correctness; changing it after writing persistent bucket IDs requires a migration.
Common Mistakes
- Do not mix truncating division with floorMod.
- Do not assume the % result is nonnegative for a negative dividend.
- Do not accept a zero or negative bucket width under this contract.
Read next
Java operators and numeric promotion, Java Math.abs on Integer.MIN_VALUE: detect the one value that cannot turn positive, Java checked integer arithmetic: reject overflow before updating state, Java arrays and bounds.
