What is Math.floorDiv in Java?

Overview

Floor division is a regular division operation, except it yields the largestclosest to positive infinity possible value that is less than or equal to the algebraic quotient. This number is less than or equal to the result of conventional division.

  • If the dividend and divisor are Integer.MIN_VALUE and -1, respectively, then the division operation results in integer overflow. Hence, the result will be Integer.MIN_VALUE.
  • If the dividend and divisor are of the same sign, then the results of floorDiv and the normal division operation are the same.
  • If the dividend and divisor are of different signs, then floorDiv returns 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 23/423/4.

The normal division operation results in 5.755.75 as the quotient.

The floor division operation results in 55 as the quotient.

Example 2

  • dividend - -23
  • divisor - 4

The fractional representation would be 23/4-23/4.

The normal division operation results in 5.755.75 as the quotient.

The floor division operation results in 6-6, 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: dividend
  • int 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);
}
}

Free Resources