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)); // -4

Powers, 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));   // 7

Rounding 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.

MethodPurposeMath.method(4.3)
Math.round()Nearest whole number4
Math.ceil()Round up to the next whole5.0
Math.floor()Round down to the previous whole4.0
Math.abs()Positive version of a number4.3

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.
Note: Math.random() never returns exactly 1.0, so (int)(Math.random() * 6) gives 0 through 5, never 6. Add 1 to shift the range to 1 through 6.

Exercise: Java Math

What range of values can Math.random() produce?