Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 201 ยท Variables and Types

The Math Class

Master Java's Math class - abs, pow, sqrt, hypot, max and min, round vs floor vs ceil, clamp, floorDiv and floorMod, trigonometry, and Math.random vs Random vs RandomGenerator.

Java's operators cover the basics: +, -, *, / and %. Everything beyond that, such as powers, square roots, rounding, absolute values, trigonometry and logarithms, lives in the java.lang.Math class. It's a toolbox of static methods: you never create a Math object, you just call Math.sqrt(16) or Math.max(a, b). Because it's in java.lang, it's available in every Java file without an import.

The methods are fast (many compile down to a single CPU instruction) and carefully specified, but several have behavior worth knowing in detail: Math.round returns a long, Math.pow loses precision on big integers, Math.abs can return a negative number, and Math.sin(Math.PI) isn't exactly zero. This lesson covers the methods you'll use daily, the pitfalls behind them, and how to generate random numbers properly.

Constants: PI, E and TAU

Math defines three constants, all double:

Constant Value Meaning
Math.PI 3.141592653589793 ratio of a circle's circumference to its diameter
Math.TAU 6.283185307179586 2ฯ€, one full turn in radians (Java 19+)
Math.E 2.718281828459045 base of natural logarithms
Java
double radius = 2.5;
double area = Math.PI * radius * radius;
double circumference = Math.TAU * radius;

Absolute value, max and min

  • Math.abs(x) returns the distance from zero: Math.abs(-7) is 7, Math.abs(-7.5) is 7.5.
  • Math.max(a, b) and Math.min(a, b) return the larger or smaller of two values. For three or more, nest them: Math.max(Math.max(a, b), c).
  • Math.signum(x) returns -1.0, 0.0 or 1.0 depending on the sign (for float and double only).

Every one of these has overloads for int, long, float and double. Java picks the overload from the argument types after normal widening, so Math.max(3, 7.5) widens 3 to 3.0 and returns the double 7.5.

Java abs, max, min and their edge cases

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Two surprises appear here. Math.abs(Integer.MIN_VALUE) returns -2147483648, because the positive version doesn't fit in an int (see Working with Numbers); Math.absExact throws instead. And if either argument of max or min is NaN, the result is NaN.

Powers and roots

Method Example Result
Math.pow(base, exponent) Math.pow(2, 10) 1024.0
Math.sqrt(x) Math.sqrt(2) 1.4142135623730951
Math.cbrt(x) Math.cbrt(-27) -3.0
Math.hypot(x, y) Math.hypot(3, 4) 5.0 (โˆš(xยฒ + yยฒ))
Math.exp(x) Math.exp(1) 2.718281828459045 (eหฃ)
Math.log(x) Math.log(Math.E) 1.0 (natural log)
Math.log10(x) Math.log10(1000) 3.0

All of them take and return double. Java has no ** or ^ power operator: 2 ^ 10 compiles, but ^ is bitwise XOR and gives 8 (see Bitwise and Shift Operators).

A few practical notes:

  • Math.sqrt of a negative number is NaN, not an error. So is Math.log of a negative number; Math.log(0) is -Infinity.
  • Math.hypot computes a distance without overflowing intermediate results, even for huge coordinates, so prefer it to Math.sqrt(x * x + y * y).
  • For a logarithm in any base, divide: Math.log(x) / Math.log(base). For base 2 of an integer, 31 - Integer.numberOfLeadingZeros(n) is exact.
  • For squaring, x * x is clearer and faster than Math.pow(x, 2).

Math.pow and big integers

Because pow works in double, it can't represent large whole numbers exactly. Above 2โตยณ, the low digits are rounded:

Java pow, roots and a precision trap

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The last digits differ (...267 vs ...256). For exact integer powers, multiply in a loop with long (and Math.multiplyExact if overflow is possible), or use BigInteger.pow from BigInteger and BigDecimal.

Rounding: round, floor, ceil and rint

Java has four rounding methods, and they differ in direction and return type:

Method 2.5 2.4 -2.5 -2.6 Returns
Math.round(x) 3 2 -2 -3 long (or int for a float)
Math.floor(x) 2.0 2.0 -3.0 -3.0 double, always down
Math.ceil(x) 3.0 3.0 -2.0 -2.0 double, always up
Math.rint(x) 2.0 2.0 -2.0 -3.0 double, ties to even
  • Math.round rounds to the nearest whole number, with halves going up toward positive infinity (so -2.5 becomes -2). It returns a long for a double argument, so int n = Math.round(2.7); fails to compile: write (int) Math.round(2.7).
  • Math.floor rounds toward negative infinity and Math.ceil toward positive infinity. Both return double.
  • Math.rint rounds ties to the nearest even number ("banker's rounding"), which avoids an upward bias when you round many values.
  • A plain cast (int) x truncates toward zero, which is different from floor for negative numbers (Type Casting and Conversion has the details).

A common need is rounding to a number of decimal places. The quick trick is to scale, round and scale back, but floating point can bite:

Java Rounding methods compared

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

1.005 * 100 is really 100.49999999999999 in binary, so the trick rounds it down. For display, format with printf("%.2f", x) or String.format instead (see Formatting Strings). For money, use BigDecimal.setScale(2, RoundingMode.HALF_UP), which rounds the exact decimal value.

Clamping a value into a range

Keeping a value between a minimum and a maximum is so common that Java 21 added Math.clamp(value, min, max). Before that, you'd write Math.max(min, Math.min(max, value)), which is easy to get backwards.

Java
int volume = Math.clamp(userVolume, 0, 100);          // never below 0 or above 100
double opacity = Math.clamp(rawOpacity, 0.0, 1.0);

clamp has overloads for int/long and float/double. One handy version takes a long value with int bounds and returns an int, so you can safely squeeze a long into an int range. If min is greater than max, it throws an IllegalArgumentException rather than quietly returning nonsense.

floorDiv and floorMod

Integer division / truncates toward zero, and % takes the sign of the left operand. That's fine for positive numbers but awkward when values can be negative, for example when you wrap around a circular list. Math.floorDiv and Math.floorMod round toward negative infinity instead, and floorMod(x, n) with a positive n always lands in 0 to n - 1:

Expression Result Expression Result
-7 / 2 -3 Math.floorDiv(-7, 2) -4
-7 % 2 -1 Math.floorMod(-7, 2) 1
-1 % 7 -1 Math.floorMod(-1, 7) 6
Java Wrapping around with floorMod and clamping

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

days[(today - 3) % 7] would throw ArrayIndexOutOfBoundsException because the index is -2. floorMod gives 5 (Sat) as intended. In the clamp loop, casting to long selects the clamp(long, int, int) overload, which returns an int and also guarantees the addition itself can't overflow.

Trigonometry

The trigonometric methods work in radians, not degrees. A full circle is 2ฯ€ radians (Math.TAU), and two helpers convert:

  • Math.sin(a), Math.cos(a), Math.tan(a): sine, cosine, tangent of an angle in radians
  • Math.asin(x), Math.acos(x), Math.atan(x): the inverses, returning radians
  • Math.atan2(y, x): the angle of the point (x, y), correct in all four quadrants
  • Math.toRadians(degrees), Math.toDegrees(radians)
Java Angles and a point on a circle

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

sin(30ยฐ) prints 0.49999999999999994 and sin(ฯ€) prints 1.2246467991473532E-16 instead of 0, because Math.PI itself is only the closest double to ฯ€. Format results for display and compare with a tolerance, as you learned for all floating-point values. (In the printf output, a tiny -0.0 can appear for coordinates that should be zero; that's negative zero, also covered in Working with Numbers.)

java.lang.StrictMath has the same methods as Math with bit-for-bit identical results on every platform. Since Java 17, all floating-point arithmetic is strict anyway, and Math is allowed to use faster CPU instructions for some functions. For nearly all programs, Math is the right choice.

Random numbers: Math.random, Random and RandomGenerator

Java offers several ways to get random numbers, from quick to flexible:

Math.random() returns a double from 0.0 (inclusive) to 1.0 (exclusive). To get a whole number in a range, scale and truncate:

Java
double r = Math.random();                    // 0.0 <= r < 1.0
int die = (int) (Math.random() * 6) + 1;     // 1 to 6

That formula is easy to get wrong (forget the parentheses and you always get 1), so for anything beyond a one-liner, use a generator object.

java.util.Random is a classic generator with convenient methods. Since Java 17 it also has range methods, so the arithmetic disappears:

Java
var random = new Random();
int die = random.nextInt(1, 7);      // 1 to 6 (upper bound exclusive)
int index = random.nextInt(10);      // 0 to 9
double d = random.nextDouble();      // 0.0 to 1.0
boolean coin = random.nextBoolean();

java.util.random.RandomGenerator (Java 17) is the modern interface that Random and newer, higher-quality algorithms all implement. RandomGenerator.getDefault() gives you a good general-purpose generator, and RandomGenerator.of("L64X128MixRandom") picks a specific algorithm. Write methods that accept a RandomGenerator so callers can pass any implementation.

Java Random numbers, reproducible with a seed

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Run it a few times: the seeded lines stay the same on every run (and on every JVM, because the Random algorithm is fully specified), while the six counts change but stay close to 1,000 each.

Which one should you use?

  • Math.random(): a quick one-off random double.
  • Random / RandomGenerator.getDefault(): games, simulations, shuffling, sampling; use a seed when you need repeatable results.
  • ThreadLocalRandom.current(): random numbers in multi-threaded code without contention.
  • java.security.SecureRandom: anything security-related, such as passwords, tokens or keys. The others are predictable if someone sees enough output.

Seeds, shuffling, sampling and secure randomness are covered in depth in Random Numbers.

Overflow-safe arithmetic

Math also contains the exact arithmetic methods you met in Working with Numbers: addExact, subtractExact, multiplyExact, negateExact, incrementExact, decrementExact, toIntExact and absExact. They behave like the normal operators on int and long, but throw ArithmeticException on overflow instead of wrapping around. Use them when a silently wrong number would be worse than a crash.

Floating-point helpers: ulp, nextUp, copySign, scalb and friends

A handful of lesser-known methods let you work with the IEEE 754 representation of a double directly. You will rarely need them in business code, but they are handy in numeric libraries, tests and when you want to understand floating-point behavior.

Method What it does
Math.ulp(x) The gap between x and the next larger double ("unit in the last place")
Math.nextUp(x), Math.nextDown(x) The adjacent double above or below x
Math.nextAfter(x, direction) The adjacent double to x in the direction of a second value
Math.getExponent(x) The unbiased binary exponent, so x is roughly 2exponent
Math.scalb(x, n) x * 2^n, computed exactly without a power call
Math.copySign(magnitude, sign) The magnitude of the first argument with the sign of the second (works for -0.0)
Math.IEEEremainder(a, b) The IEEE remainder: a - b * n, where n is the integer nearest a / b
Math.fma(a, b, c) a * b + c with a single rounding step (Java 9+)

Math.IEEEremainder differs from the % operator. % truncates the quotient toward zero, so its result has the sign of the dividend; IEEEremainder rounds the quotient to the nearest integer (ties to even), so the result can be negative even when both inputs are positive.

Java Floating-point helper methods

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

10 % 3 is 1.0 and so is IEEEremainder(10, 3) (10 / 3 is about 3.33, which rounds to 3). For 11 and 4 the quotient 2.75 rounds to 3, so the IEEE remainder is 11 - 12 = -1.0, while 11 % 4 would be 3.0. ulp(1.0) is 2-52, which is why adding anything smaller than about 2.2e-16 to 1.0 changes nothing. Use nextUp and nextDown to build "just above" or "just below" boundaries in tests, and ulp to choose a sensible tolerance when comparing double values.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does int n = Math.round(4.6); fail to compile?

    Math.round has two overloads, round(float) returning int and round(double) returning long. 4.6 is a double, so the result is a long. Write (int) Math.round(4.6).
  2. 2. What does Math.floor(-3.2) return?

    floor always rounds toward negative infinity, so -3.2 goes down to -4, and floor returns a double. A cast (int) -3.2 would truncate to -3 instead.
  3. 3. What is Math.floorMod(-2, 5)?

    floorMod with a positive divisor always returns a value from 0 to divisor - 1. Since -2 = -1 ร— 5 + 3, the result is 3. The % operator would give -2.
  4. 4. Which call returns a random whole number from 1 to 6 inclusive?

    nextInt(origin, bound) includes the origin and excludes the bound, so (1, 7) gives 1 to 6. The first option casts Math.random() to 0 before multiplying, so it always gives 1, and the last can give 0.
  5. 5. What does Math.clamp(250, 0, 100) return?

    clamp limits the value to the range from min to max. 250 is above the maximum, so the result is 100.

Summary

  • Math is a class of static methods in java.lang; it also defines Math.PI, Math.TAU and Math.E.
  • abs, max, min have overloads for every numeric type; Math.abs(Integer.MIN_VALUE) stays negative, so use absExact when that matters.
  • pow, sqrt, cbrt, hypot, exp, log and log10 work in double; sqrt of a negative number is NaN, and pow loses precision for big integers. ^ is XOR, not a power.
  • round (halves up, returns long/int), floor (down), ceil (up) and rint (ties to even) round differently; a cast truncates toward zero. Format with printf for display, and use BigDecimal for money.
  • Math.clamp (Java 21) keeps a value in a range; floorDiv, floorMod and ceilDiv handle negative numbers and page counts cleanly.
  • Trigonometry uses radians; convert with toRadians/toDegrees, and expect tiny floating-point errors.
  • Use Math.random() for quick values, Random/RandomGenerator with nextInt(origin, bound) for real work (seed for repeatability), and SecureRandom for security.

Next: Arithmetic Operators, where you'll look closely at + - * / %, string concatenation and numeric promotion.