Library contents

Java Math.floorMod

Floor modulus gives a wrapped index for a positive cycle length.

A simple example

Math.floorMod

  1. Start with −7 and 3
  2. Do this Use the floor quotient −3
  3. Result 2
Three times −3 gives −9. Add 2 to reach −7.
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        System.out.println(Math.floorMod(-7, 3));
    }
}
Output
2

Syntax

Java syntax
Math.floorMod(position, shelves)
JDK 21 method signatures (3)
public static int floorMod(int x, int y)
public static int floorMod(long x, int y)
public static long floorMod(long x, long y)
Run these examples in Java

Save one example at a time as Main.java. Use JDK 21.

java Main.java

Wrap a shelf position back to the last shelf

A picker cycles through a fixed set of shelves and can step backwards from the first position. Map that earlier position back into the valid shelf range before indexing the list.

From the programint position = -1
Result6
Main.java

class Main {
    public static void main(String[] args) throws Exception {
        int position = -1;
        int shelves = 7;
        System.out.println(Math.floorMod(position, shelves));
    }
}
Output
6

Moving back from shelf zero produces shelf six in a seven-shelf cycle.

Advertisements

Locate a complete carousel turn

A carousel holds six numbered trays. After twelve forward steps the indexing routine checks the remainder at a complete turn.

Given12 steps · 6 trays
Worked result0

An exact number of turns gives zero with either rounding convention.

Step back on a weekly rota

A seven-day rota stores Monday at index zero. An editor moves back two days and needs an index that still lies inside the rota.

GivenStart 0 · step −2 · width 7
Worked result5

With a positive width, floor modulus wraps the negative step to index five.

What to watch for

Supply a positive cycle length for an index in the range zero through length minus one.

Documentation for Math.floorMod