Java Math Class — abs, pow, random, sqrt & More

2 minute read

The java.lang.Math class provides static methods for common mathematical operations. Since it’s in java.lang, no import is needed.


Constants

Math.PI   // 3.141592653589793
Math.E    // 2.718281828459045

Basic Operations

Math.abs(-7)        // 7
Math.abs(-3.14)     // 3.14

Math.max(10, 20)    // 20
Math.min(10, 20)    // 10

Math.max(Math.max(a, b), c)  // max of three

Power and Roots

Math.pow(2, 10)     // 1024.0   (2^10)
Math.sqrt(144)      // 12.0
Math.cbrt(27)       // 3.0      (cube root)

// Square root of negative → NaN
Math.sqrt(-1)       // NaN

Rounding

Math.round(3.5)     // 4   (long) — rounds half-up
Math.round(3.4)     // 3
Math.round(-3.5)    // -3  (rounds towards positive infinity)

Math.ceil(3.1)      // 4.0  (always rounds up)
Math.ceil(-3.1)     // -3.0

Math.floor(3.9)     // 3.0  (always rounds down)
Math.floor(-3.9)    // -4.0
Method 3.2 3.5 3.8 -3.2 -3.5 -3.8
round 3 4 4 -3 -3 -4
ceil 4.0 4.0 4.0 -3.0 -3.0 -3.0
floor 3.0 3.0 3.0 -4.0 -4.0 -4.0

Logarithms and Exponentials

Math.log(Math.E)    // 1.0     (natural log)
Math.log10(1000)    // 3.0     (base-10 log)
Math.exp(1)         // 2.7182... (e^1)

Trigonometry

Math.sin(Math.PI / 2)  // 1.0
Math.cos(0)             // 1.0
Math.tan(Math.PI / 4)  // ~1.0

Math.toRadians(180)     // π
Math.toDegrees(Math.PI) // 180.0

Random Numbers with Math.random()

Returns a double in the range [0.0, 1.0):

double r = Math.random();  // e.g., 0.7342...

Random Int in a Range

// Random int from min (inclusive) to max (inclusive)
int min = 1, max = 100;
int random = (int) (Math.random() * (max - min + 1)) + min;

The Random Class

More features than Math.random():

import java.util.Random;

Random rand = new Random();

rand.nextInt()           // any int
rand.nextInt(100)        // 0 to 99
rand.nextInt(10, 20)     // 10 to 19 (Java 17+)
rand.nextDouble()        // 0.0 to 1.0
rand.nextBoolean()       // true or false
rand.nextGaussian()      // normal distribution (mean=0, sd=1)

Seeded Random (Reproducible)

Random rand = new Random(42);  // same seed → same sequence
rand.nextInt(100)  // always same value for same seed

ThreadLocalRandom — Multi-Threaded

import java.util.concurrent.ThreadLocalRandom;

int r = ThreadLocalRandom.current().nextInt(1, 101);  // 1 to 100

Prefer ThreadLocalRandom over Random in multi-threaded applications — no contention.


Practical Examples

Distance Between Two Points

public static double distance(double x1, double y1, double x2, double y2) {
    return Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2));
}
// Or use Math.hypot(x2-x1, y2-y1) — handles overflow better

Compound Interest

public static double compoundInterest(double principal, double rate,
                                       int years, int timesPerYear) {
    return principal * Math.pow(1 + rate / timesPerYear, timesPerYear * years);
}

Dice Roll Simulator

Random rand = new Random();
int die1 = rand.nextInt(1, 7);  // 1 to 6
int die2 = rand.nextInt(1, 7);
System.out.printf("Rolled: %d + %d = %d%n", die1, die2, die1 + die2);

Quick Reference

Method Description Example
abs(x) Absolute value abs(-5) → 5
max(a,b) Larger value max(3,7) → 7
min(a,b) Smaller value min(3,7) → 3
pow(a,b) a to the power b pow(2,3) → 8.0
sqrt(x) Square root sqrt(16) → 4.0
round(x) Round to nearest round(3.6) → 4
ceil(x) Round up ceil(3.1) → 4.0
floor(x) Round down floor(3.9) → 3.0
random() Random [0, 1) random() → 0.73…
log(x) Natural log log(E) → 1.0

Key Takeaways

  1. Math methods are all static — call as Math.method().
  2. Use Math.random() for quick random numbers; Random for more control.
  3. Use ThreadLocalRandom in multi-threaded code.
  4. Math.round() rounds half-up; ceil always up; floor always down.
  5. Seed Random for reproducible sequences (testing, simulations).

What’s Next?

Next: Java Dates and Time — the modern java.time API with LocalDate, LocalDateTime, ZonedDateTime, and formatting.

Updated: