Math And Random Numbers
The Math class provides numeric helpers, while Random produces pseudorandom values from an internal state.
Supplying a seed makes a sequence repeatable. That is useful in examples and tests; ordinary production randomness can use an unseeded generator.
Repeat a random sequence
import java.util.Random;
public class Main {
public static void main(String[] args) {
long seed = 42L;
Random random = new Random(seed);
int gameCode = random.nextInt(900) + 100;
System.out.println(gameCode);
System.out.println(Math.abs(-12));
System.out.println(Math.max(4, 9));
}
}
Output:
630
12
9
nextInt(900) + 100 shifts the range 0 through 899 into three-digit game codes 100 through 999. Math.abs returns the magnitude of -12, and Math.max returns the larger of its two arguments.
Math helpers you will reach for most:
| Method | Returns |
|---|---|
Math.abs(x) | The magnitude of x |
Math.max(a, b) | The larger of the two |
Math.min(a, b) | The smaller of the two |
Math.pow(a, b) | a raised to b, as a double |
Math.sqrt(x) | The square root, as a double |
Math.round(x) | The nearest whole number |
Random is not suitable for passwords or security tokens. Use SecureRandom when unpredictability protects users or data.
Seed Random, roll a number from 1 through 6, then print the larger of 8 and 12.