Java Math
The Java Math class is a toolbox of ready-made methods for common calculations, from rounding and powers to square roots and random numbers. Because every method is static, you call it directly on the class name without creating an object.
Finding the Bigger or Smaller Value
Math.max() returns the larger of two numbers and Math.min() returns the smaller. Both accept two values of the same type and are perfect when you need to keep a value within a range or pick a winner between two options.
max and min
System.out.println(Math.max(8, 15)); // 15
System.out.println(Math.min(8, 15)); // 8
System.out.println(Math.max(-4, -9)); // -4Powers, Roots, and Absolute Values
Math.pow() raises a number to a power, Math.sqrt() computes a square root, and Math.abs() gives the distance of a number from zero, always as a positive value. These three cover a large share of everyday number crunching.
Core math methods
System.out.println(Math.pow(2, 5)); // 32.0
System.out.println(Math.sqrt(144)); // 12.0
System.out.println(Math.abs(-7)); // 7Rounding Numbers
Java offers three ways to round. Math.round() moves to the nearest whole number, Math.ceil() always rounds up, and Math.floor() always rounds down. The table shows how each one treats the same input.
Random Numbers
Math.random() returns a double from 0.0 up to (but not including) 1.0. To get a whole number in a range, multiply by the range size, cast to int, and shift as needed. The example produces a value from 1 to 6, like a dice roll.
A dice roll
int roll = (int) (Math.random() * 6) + 1;
System.out.println("You rolled: " + roll); // 1 to 6- Every Math method is static, so call it as Math.methodName().
- Math.pow(), Math.sqrt(), Math.ceil(), and Math.floor() return a double.
- Math.PI and Math.E are handy built-in constants for geometry and growth formulas.
- For repeated or more flexible random numbers, the java.util.Random class is a good alternative.
Exercise: Java Math
What range of values can Math.random() produce?