VOOZH about

URL: https://www.geeksforgeeks.org/java/java-math-floormod-method/

⇱ Java Math floorMod() Method - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Java Math floorMod() Method

Last Updated : 13 May, 2025

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.

Syntax of floorMod() Method

public static int floorMod(int a, int b)

public static long floorMod(long a, long b)

  • Parameters:
    • a: the dividend (number to be divided)
    • b: the divisor
  • Return Value: It returns the remainder after division, where the result always carries the sign of the divisor
  • Exception: If the divisor is 0, it throws an ArithmeticException.

Examples of Java Math floorMod() Method

Example 1: In this example, we are going see how floorMod() method handles different sign cases.


Output
Result 1: 0
Result 2: 23
Result 3: -27
Result 4: 27

Explanation: In this example,

  • In the first case, we start with 25 mod 5 and for this, the remainder is 0.
  • In the second case, we use 123 mod 50. So, 123 / 50 = 2 with a remainder of 23.
  • In the third case, we use 123 mod -50. This returns -27 because it follows the negative sign of the divisor.
  • In the fourth example, we use -123 mod 50. The result is 27 because it follows the divisor's sign.


Example 2: In this example, we will perform the division by zero case.

Output:

Exception in thread "main" java.lang.ArithmeticException: / by zero

Explanation: 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.


When to Use floorMod() Instead of %

We should use floorMod() when:

  • We want the result to match the sign of the divisor.
  • We are dealing with negative numbers and want consistent behavior.
  • We are implementing modular arithmetic such as clock or calendar calculations.
Comment
Article Tags: