It’s good to familiarize yourself with the ceil function in mathematics before we move to the ceil method in Java.
“A ceil function converts a decimal number to the immediate largest integer.”
If the number passed is already a whole number or an integer, then the same number is the ceiling value. However, if you pass a null value to the ceil function in mathematics you get a “zero”.
What is the ceil function in mathematics?
What is the Math.ceil() method in Java?
Java provides a built-in method to compute the ceil function in mathematics. That we can freely use by passing a “double” type argument to the method Math.ceil(). Let’s have a look at some boundary cases prior to moving to the use cases.- If the parameter “double” is also a mathematical “integer” [eg: 2.0 is the same as 2] - The result is equal to the integer [i-e; 2 itself].
- If the parameter (let parameter = x) is less than 0 but greater than -1 [ -1 > x < 0 ] - Result is equal to negative zero [-0].
- If the parameter is NaN, +0, -0 or ∞ - Result is the same as the parameter.
- If the parameter is “null” - unlike the mathematical ceil function where you get a zero, here you’ll get a java.lang.NullPointerException.
Example
class Main {
public static void main(String[] args) {
Double totalStudentsInClass = 25.0;
Double flourWeightInKgs = 5.13;
Double aPoundOfOxygenInLitres = 0.3977;
Double startingArrayIndexInJava = 0.0;
Double aSelfDrivingCar = Double.NaN;
Double numberOfStarsInTheSky = Double.POSITIVE_INFINITY;
// For parameter [ -1 > x < 0 ]
Double x = -0.025;
// using Math.ceil() method
System.out.println("Total Students In Class = " + Math.ceil(totalStudentsInClass));
System.out.println("Flour Weight In Kgs = " + Math.ceil(flourWeightInKgs));
System.out.println("A Pound of Oxygen in Litres = " + Math.ceil(aPoundOfOxygenInLitres));
System.out.println("Starting Array Index In Java = " + Math.ceil(startingArrayIndexInJava));
System.out.println("A Self Driving Car = " + Math.ceil(aSelfDrivingCar));
System.out.println("Number Of Stars In The Sky = " + Math.ceil(numberOfStarsInTheSky));
System.out.println("Positive Zero = " + Math.ceil(+0.0));
System.out.println("Negative Zero = " + Math.ceil(-0.0));
System.out.println("x = " + x + " [ -1 > x < 0 ] = " + Math.ceil(-0.0));
}
}
Output
Total Students In Class = 25.0
Flour Weight In Kgs = 6.0
A Pound of Oxygen in Litres = 1.0
Starting Array Index In Java = 0.0
A Self Driving Car = NaN
Number Of Stars In The Sky = Infinity
Positive Zero = 0.0
Negative Zero = -0.0
x = -0.025 [ -1 > x < 0 ] = -0.0
GO TO FULL VERSION