Math FloorDiv FloorMod Wrap Around

Tell truncating division and floor division apart: % keeps the dividend sign while Math.floorMod always lands in 0..divisor-1, ideal for circular indexing.

JavaData Integrity

Code

snippet
public class CircularIndexing {

    public static void main(String[] args) {
        // 截断除法:商向零取整,余数符号跟随被除数
        System.out.println(-7 / 2 + " remainder " + -7 % 2);

        // floor 语义:商向下取整,余数符号跟随除数
        System.out.println(Math.floorDiv(-7, 2) + " remainder " + Math.floorMod(-7, 2));

        // 环形缓冲:head 前进或倒退任意步,负步长也能正确回绕到合法槽位
        int capacity = 5;
        int head = 1;
        for (int step : new int[] {3, -2, -6}) {
            int wrapped = Math.floorMod(head + step, capacity);
            System.out.println("head=" + head + " step=" + step + " -> slot " + wrapped);
        }

        // 负数直接用 % 会落到负槽位,floorMod 恒为非负
        System.out.println("plain %: " + (-2 % 5));
        System.out.println("floorMod: " + Math.floorMod(-2, 5));
    }
}

How it works

Math FloorDiv FloorMod Wrap Around reduces to the class CircularIndexing and the function main.

Iteration happens inside for (int step : new int[] {3, -2, -6}) — everything outside it runs once.

Using it

Running the file prints labeled results such as head=, plain %:, floorMod: — each operation’s effect is visible in the output.

Key statements

int wrapped = Math.floorMod(head + step, capacity);
int capacity = 5;
int head = 1;

Interactive Tools for This Topic

FAQ

What does Math FloorDiv FloorMod Wrap Around print when run?
No setup needed: run the file and look for labeled lines like `head=`, `plain %:`, `floorMod:` in the output.