Java Math.ceilDiv
Integer ceiling division rounds the quotient up without converting to floating point.
A simple example
Math.ceilDiv
- Start with 7 divided by 3
- Do this Round the quotient up
- Result 3
class Main {
public static void main(String[] args) throws Exception {
System.out.println(Math.ceilDiv(7, 3));
}
}
3
Syntax
Math.ceilDiv(orders, capacity)
JDK 21 method signatures (3)
public static int ceilDiv(int x, int y)
public static long ceilDiv(long x, int y)
public static long ceilDiv(long x, long y)Run these examples in Java
Save one example at a time as Main.java. Use JDK 21.
java Main.javaCount crates for an order
A dispatch team packs an order into crates of a fixed capacity. Work out how the order fits the packing rule when the quantity does not divide evenly.
class Main {
public static void main(String[] args) throws Exception {
int orders = 17;
int capacity = 4;
System.out.println(Math.ceilDiv(orders, capacity));
}
}
5
Four full crates carry sixteen items and a fifth holds the remaining item.
Pack badges for two classrooms
A teacher has 31 badges and uses trays that hold eight each. All badges must travel, including those in a partially filled tray.
Three trays carry 24 badges. The remaining seven need the fourth tray.
Send a full print batch
A print shop has 48 cards and cartons that hold twelve each. The packer checks whether another carton is needed after the fourth.
An exact multiple leaves no partial carton.
What to watch for
The divisor must be nonzero. For packing work a negative capacity is meaningless.