![]() |
VOOZH | about |
The Math.floorMod() is a built-in math function in Java that returns the floor modulus of the integer arguments passed to it. Therefore, floor modulus is (a - (floorDiv(a, b) * b)), has the same sign as the divisor b, and is in the range of -abs(b) < result < +abs(b). The relationship between floorDiv() and floorMod() is:
floorDiv(a, b) * b + floorMod(a, b) == a
The difference in results between floorMod and the % operator is due to the difference between floorDiv() which returns the integer less than or equal to the quotient, and the "/ " operator that returns the integer closest to zero.
public static int floorMod(int a, int b)
public static long floorMod(long a, long b)
Example 1: In this example, we are going see how floorMod() method handles different sign cases.
Result 1: 0 Result 2: 23 Result 3: -27 Result 4: 27
Explanation: In this example,
Example 2: In this example, we will perform the division by zero case.
Output:
Exception in thread "main" java.lang.ArithmeticException: / by zeroExplanation: In this example, we try to divide 200 by 0, which is not allowed in Java. So the output of the program throws an ArithmeticException.
We should use floorMod() when: