The difference between Math.floorMod() and % in java

Viewed 10029

could anybody tell me the difference between Math.floorMod() and % in java?

I was quite confused when

    int a = 3;
    int b = -2;
    System.out.println(a % b);
    System.out.println(Math.floorMod(a,b));

And the result is 1 -1 instead of 1 1

1 Answers

As per the javadocs

If the signs of the arguments are the same, the results of floorMod and the % operator are the same.

floorMod(4, 3) == 1;   and (4 % 3) == 1

If the signs of the arguments are different, the results differ from the % operator.

floorMod(+4, -3) == -2;   and (+4 % -3) == +1
floorMod(-4, +3) == +2;   and (-4 % +3) == -1
floorMod(-4, -3) == -1;   and (-4 % -3) == -1
Related