Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

Math.floorMod()

A remainder that always has the sign of the divisor.

Available since: Java 8

Syntax

static int floorMod(int x, int y)

Parameters

ParameterTypeDescription
xint / longThe dividend.
yint / longThe divisor.

Return value

int / longFor a positive y, a number from 0 to y - 1.

Examples

Compared with the % operator:

void main() {
    IO.println(-1 % 7);
    IO.println(Math.floorMod(-1, 7));
}

Output:

-1
6

A weekday "in a circle": 3 days before Monday (index 0):

void main() {
    String[] days = {"Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"};
    int index = Math.floorMod(0 - 3, 7);
    IO.println(days[index]);
}

Output:

Fri

Notes

For positive numbers floorMod() and % give the same result. They differ only for a negative dividend — exactly where % gives an awkward negative array index. Its partner Math.floorDiv() divides rounding down.

See also

  • % — Returns the remainder of a division.
  • Math.floor() — Rounds down to the nearest integer that is less than or equal.

Related recipes

In the tutorial

  • Operators — Java arithmetic operators, integer division and remainder, compound assignment, increment, comparison and logical operators.

Thanks for reading!

Donate to the site — we work hard for you.