Java Random Numbers
Games roll dice, quizzes shuffle questions, simulations need unpredictable events. You met Math.random() in the Math topic; the java.util.Random class is easier to use and offers much more. Its numbers are pseudo-random: they are calculated from a starting value called the seed, but they look random and are spread evenly.
Random numbers in a range
nextInt(bound) returns a whole number from 0 up to, but not including, bound. nextInt(origin, bound) returns one from origin up to bound (not included). The values change on every run, so this example checks that they are in range:
import java.util.Random;
public class Main {
public static void main(String[] args) {
Random rnd = new Random();
boolean allOk = true;
for (int i = 0; i < 1000; i++) {
int dice = rnd.nextInt(1, 7);
if (dice < 1 || dice > 6) {
allOk = false;
}
}
System.out.println("1000 dice rolls, all from 1 to 6: " + allOk);
}
}1000 dice rolls, all from 1 to 6: true
In your own programs, just print dice and run the program several times to see different numbers.
A seed makes results repeatable
When you give Random a seed, it produces the same sequence every time. That is very useful for testing and for games where players share a "level code". This program always prints the same numbers:
import java.util.Random;
public class Main {
public static void main(String[] args) {
Random rnd = new Random(42);
for (int i = 0; i < 5; i++) {
System.out.print(rnd.nextInt(100) + " ");
}
System.out.println();
System.out.println(rnd.nextBoolean());
System.out.printf("%.3f%n", rnd.nextDouble());
}
}30 63 48 84 70 true 0.277
nextBoolean() returns true or false with equal chance, and nextDouble() a decimal number from 0.0 up to 1.0.
Simulating many events
Random numbers are perfect for experiments that would take too long by hand. This program rolls two dice 6,000 times and counts how often each total appears, using an array as a set of counters:
import java.util.Random;
public class Main {
public static void main(String[] args) {
Random rnd = new Random(7);
int[] counts = new int[13];
for (int i = 0; i < 6000; i++) {
int total = rnd.nextInt(1, 7) + rnd.nextInt(1, 7);
counts[total]++;
}
for (int t = 2; t <= 12; t++) {
System.out.printf("%2d: %s%n", t, "#".repeat(counts[t] / 50));
}
}
}2: ### 3: ###### 4: ######### 5: ############## 6: ############### 7: ################### 8: ################ 9: ############## 10: ######### 11: ###### 12: ###
The bars show that 7 is the most common total, because the most combinations of two dice add up to it.
Shuffling and picking
Collections.shuffle puts a list in random order, and a random index picks one item:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
public class Main {
public static void main(String[] args) {
Random rnd = new Random(2025);
List<String> questions = new ArrayList<>(List.of("Q1", "Q2", "Q3", "Q4", "Q5"));
Collections.shuffle(questions, rnd);
System.out.println(questions);
String[] prizes = {"pen", "book", "cap", "mug"};
System.out.println("You win a " + prizes[rnd.nextInt(prizes.length)]);
}
}[Q4, Q3, Q5, Q1, Q2] You win a cap
For passwords and security codes, use java.security.SecureRandom instead: its numbers cannot be predicted, even by someone who knows earlier ones.
Practice exercises
- Write a number guessing game: pick a random number from 1 to 100 and let the user guess with "higher" and "lower" hints.
- Flip a coin 1,000 times and print how many heads and tails you got.
- Make a random password of 8 characters chosen from the letters and digits.