← Chapter 3 — Strings, Escapes & Math

15. Math Class

mixed

Description

The Math class provides common calculations without creating an object. Its methods are static, so call them with Math followed by a dot.

Math can round values, find powers, calculate square roots, and choose larger or smaller values. It helps make formulas easy to read and test.

Subtopics

Rounding

Description

round, ceil, and floor handle decimal values differently.

Explanation

Choose the method that matches the rule your program needs.

Example

long rounded = Math.round(87.6);

Powers and limits

Description

pow, sqrt, max, and min solve common tasks.

Explanation

Math.pow returns a double, even for whole-number inputs.

Example

double area = Math.pow(5, 2);

Explanation

Math.random returns a decimal from 0.0 up to but not including 1.0. For most modern random-number needs, prefer java.util.Random or ThreadLocalRandom.

Example

public class MathDemo {
    public static void main(String[] args) {
        double average = 87.6;
        System.out.println(Math.round(average));
        System.out.println(Math.max(72, 91));
    }
}

Key points

  • Math methods are static.
  • round returns the nearest whole value.
  • pow and sqrt return double values.

Open reference