Math utilities
Use java.lang.Math instead of hand-rolling rounding, powers and safe arithmetic.
Open this lesson in the learning hubKey points
Mathis nothing but static methods over primitives — you never create one.abs,max,sqrt,powandhypotcover the everyday cases.roundties upward:round(2.5)is3butround(-2.5)is-2.floorandceilreturn doubles, whilefloorModkeeps negative numbers behaving like a clock.addExactthrowsArithmeticExceptioninstead of silently wrapping — use it on money and counters.Math.random()returns a value in[0, 1). For bounded or repeatable values usejava.util.Random.
Example
public class Main {
public static void main(String[] args) {
System.out.println("abs(-7) = " + Math.abs(-7));
System.out.println("max / min = " + Math.max(3, 9) + " / " + Math.min(3, 9));
System.out.println("pow(2, 10) = " + Math.pow(2, 10) + " (always a double)");
System.out.println("sqrt(144) = " + Math.sqrt(144));
System.out.println("round(2.5) = " + Math.round(2.5) + ", round(-2.5) = " + Math.round(-2.5));
System.out.println("floor / ceil = " + Math.floor(2.7) + " / " + Math.ceil(2.1));
System.out.println("-7 / 2 = " + (-7 / 2) + " but floorDiv(-7, 2) = " + Math.floorDiv(-7, 2));
System.out.println("-7 % 3 = " + (-7 % 3) + " but floorMod(-7, 3) = " + Math.floorMod(-7, 3));
try {
Math.addExact(Integer.MAX_VALUE, 1);
} catch (ArithmeticException e) {
System.out.println("addExact refuses to wrap: " + e.getMessage());
}
System.out.println("hypot(3, 4) = " + Math.hypot(3, 4));
System.out.println("PI = " + String.format("%.5f", Math.PI));
System.out.println("random() is in [0, 1): " + (Math.random() < 1.0));
}
}
Math already solved it, and it handles the edge cases you would forget.
This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the Core Java course, and every lesson in it is listed on the Core Java contents page.