Beginner-Friendly Topic
Take your time - it's perfectly normal to re-read this topic 2-3 times. Try the interactive code editor below to run code yourself. Use the Q&A section to check your understanding before moving on.You've got this!
Lesson 3 of 10
Math & Random
The Math class provides static mathematical operations - rounding, power, root, trigonometry, min/max. The Random class generates pseudo-random numbers. For thread-safe random in concurrent code, use ThreadLocalRandom.
Math & Random API
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;
public class MathAndRandom {
public static void main(String[] args) {
// Math - all static, no instance needed
System.out.println(Math.abs(-42)); // 42
System.out.println(Math.max(10, 25)); // 25
System.out.println(Math.min(10, 25)); // 10
System.out.println(Math.pow(2, 10)); // 1024.0
System.out.println(Math.sqrt(144)); // 12.0
System.out.println(Math.cbrt(27)); // 3.0
System.out.println(Math.floor(9.7)); // 9.0
System.out.println(Math.ceil(9.1)); // 10.0
System.out.println(Math.round(9.5)); // 10 (rounds .5 up)
System.out.println(Math.PI); // 3.141592653589793
System.out.println(Math.log(Math.E)); // 1.0 (natural log)
System.out.println(Math.log10(1000)); // 3.0
// Clamp (Java 21+) - keep a value within bounds
// double clamped = Math.clamp(value, min, max);
// Random - pseudo-random (seeded)
Random random = new Random();
int rollDie = random.nextInt(6) + 1; // 1 to 6 (nextInt(6) = 0-5)
double chance = random.nextDouble(); // 0.0 to 1.0
boolean coinFlip = random.nextBoolean();
// Seeded - reproducible sequence (useful for testing)
Random seeded = new Random(42L);
System.out.println(seeded.nextInt(100)); // always 0 for seed 42
// ThreadLocalRandom - thread-safe, no sharing overhead
int threadSafeRoll = ThreadLocalRandom.current().nextInt(1, 7); // 1 to 6
double between = ThreadLocalRandom.current().nextDouble(0.5, 1.5);
// Discount calculation using Math
double originalPrice = 499.99;
double discount = 15.0; // percent
double discounted = Math.round(originalPrice * (1 - discount/100) * 100.0) / 100.0;
System.out.printf("Discounted price: $%.2f%n", discounted); // $424.99
}
}Quick Quiz
Tip
Tip
Practice Math Random in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Visual architecture and concepts for Math & Random
Practice Task
Note
Practice Task - (1) Write a working example of Math Random from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Common Mistake
Warning
A common mistake with Math Random is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready java code.
Finished this lesson?