Careeroza
Random Numbers
Math.random and Random
Math.random() returns a double from 0.0 (inclusive) to 1.0 (exclusive). The java.util.Random class gives more control. A seed makes the sequence repeatable, which is useful in tests and games replays.
double r = Math.random(); // e.g. 0.7302...
int dice = (int) (Math.random() * 6) + 1; // 1 to 6Random with a Seed
Example
With the same seed, Random always produces the same numbers, so this output is always identical.
import java.util.Random;
public class Main {
public static void main(String[] args) {
Random random = new Random(42);
for (int i = 0; i < 5; i++) {
int dice = random.nextInt(6) + 1; // 1 to 6
System.out.print(dice + " ");
}
System.out.println();
int between = random.nextInt(10, 21); // 10 to 20 (Java 17+)
System.out.println("Between 10 and 20: " + between);
}
}Output
3 4 1 3 1 Between 10 and 20: 18
Note: For passwords, OTPs and tokens use java.security.SecureRandom, which is unpredictable. Random and Math.random() are not secure.
Exercise: Write an expression that gives a random integer from 1 to 100 using Math.random().
Show answer
int n = (int) (Math.random() * 100) + 1;