The Math Class
Math is a utility class living in java.lang, which means it is available in every Java file automatically — no import required. It bundles common numeric operations as static methods, so you call them directly on the class name, like Math.sqrt(25), without ever creating a Math object.
Common Methods
Method | Purpose |
|---|---|
| Absolute value — removes the sign |
| Raises |
| Square root of |
| Larger / smaller of two values |
| Rounds to the nearest whole number |
| Rounds down / up to the nearest whole number, as a |
| Returns a random |
Using the core Math methods
public class MathBasicsDemo {
public static void main(String[] args) {
System.out.println(Math.abs(-7)); // 7
System.out.println(Math.pow(2, 10)); // 1024.0
System.out.println(Math.sqrt(81)); // 9.0
System.out.println(Math.max(3, 9)); // 9
System.out.println(Math.min(3, 9)); // 3
System.out.println(Math.round(4.6)); // 5
System.out.println(Math.floor(4.9)); // 4.0
System.out.println(Math.ceil(4.1)); // 5.0
}
}7 1024.0 9.0 9 3 5 4.0 5.0
Generating a Random Integer in a Range
Math.random() always returns a double between 0.0 and 1.0 (never reaching 1.0). To get a random integer within a specific range, you scale, shift, and cast the result yourself.
A random integer between min and max (inclusive)
public class RandomRangeDemo {
public static void main(String[] args) {
int min = 10;
int max = 20;
// Math.random() is in [0.0, 1.0), so scale by the range size,
// truncate to an int with the cast, then shift by min.
int randomValue = (int) (Math.random() * (max - min + 1)) + min;
System.out.println(randomValue); // some value in [10, 20]
}
}The same range, with java.util.Random
import java.util.Random;
public class RandomClassDemo {
public static void main(String[] args) {
Random random = new Random();
int min = 10;
int max = 20;
int randomValue = random.nextInt(max - min + 1) + min;
System.out.println(randomValue); // some value in [10, 20]
}
}Mathlives injava.lang, so noimportis needed to use it.All
Mathmethods arestatic— called asMath.methodName(...), never on an instance.Math.random()returns adoublein[0.0, 1.0)— scale and shift it manually for an integer range.java.util.RandomandThreadLocalRandomare better fits for repeated or seeded random number generation.