What is Math.floorDiv in Java?
Overview
Floor division is a regular division operation, except it yields the
- If the dividend and divisor are
Integer.MIN_VALUEand-1, respectively, then the division operation results in integer overflow. Hence, the result will beInteger.MIN_VALUE. - If the dividend and divisor are of the same sign, then the results of
floorDivand the normal division operation are the same. - If the dividend and divisor are of different signs, then
floorDivreturns the integer less than or equal to the quotient, and normal division returns the integer closest to zero.
Example 1
- dividend - 23
- divisor - 4
The fractional representation would be .
The normal division operation results in as the quotient.
The floor division operation results in as the quotient.
Example 2
- dividend - -23
- divisor - 4
The fractional representation would be .
The normal division operation results in as the quotient.
The floor division operation results in , as the quotient because the signs of the dividend and divisor are different.
The floorDiv method is introduced in Java 8.
floorDiv is defined in the Math class, which is defined in the java.lang package.
To import the Math class, use the import statement below:
import java.lang.Math;
Method signature
public static int floorDiv(int x, int y)
Parameters
int x: dividendint y: divisor
Return value
The floorDiv method returns the largest value that is less than or equal to the algebraic quotient.
Overloaded methods
public static long floorDiv(long x, int y)public static long floorDiv(long x, long y)
Code
import java.lang.Math;public class Main{public static void main(String[] args){int dividend = 23;int divisor = -4;int quotient = Math.floorDiv(dividend, divisor);System.out.printf("floorDiv(%d, %d) = %d", dividend, divisor, quotient);System.out.println();dividend = 23;divisor = 4;quotient = Math.floorDiv(dividend, divisor);System.out.printf("floorDiv(%d, %d) = %d", dividend, divisor, quotient);}}