Java ยท Chapter 11 of 42

Java Math

The Math class provides static methods for common mathematical operations like Math.max(), Math.min(), Math.pow(), Math.sqrt(), and Math.random(), without needing to create an object.

These methods save you from writing your own math logic and are optimized and well-tested.

Syntax
Math.max(a, b);
Math.pow(a, b);
Math.random();

Common Math methods

Math.max(a,b) and Math.min(a,b) find the larger/smaller value. Math.pow(base, exp) raises a number to a power. Math.sqrt(x) finds a square root.

Random numbers

Math.random() returns a double between 0.0 (inclusive) and 1.0 (exclusive), often scaled to generate random integers in a range.

Example 1 (java)
public class Main {
  public static void main(String[] args) {
    System.out.println(Math.max(5, 10));
    System.out.println(Math.pow(2, 3));
    System.out.println(Math.sqrt(16));
  }
}
Output
10
8.0
4.0

Math.max returns the larger value, Math.pow computes 2^3, and Math.sqrt computes the square root of 16.

Key points

  • Math methods are static, called without an object.
  • Math.random() returns a double between 0.0 and 1.0.
  • Math.pow and Math.sqrt handle powers and roots.
  • Math.abs() returns the absolute value.
๐Ÿ’ก Note: To get a random int in a range [0, n), use (int)(Math.random() * n).

๐Ÿ“ Quick Quiz

1. What range does Math.random() return?

2. Which method raises a number to a power?

3. Are Math methods static?