Generate Random Numbers in Java
Problem
A pseudo-random number generator produces a sequence that looks random but is fully determined by its starting value, called the seed.
Generate five dice rolls, one integer between 50 and 60 inclusive, and a coin flip.
Java Program
import java.util.Random;
public class RandomNumbers {
public static void main(String[] args) {
Random random = new Random(7); // fixed seed, so every run prints the same numbers
System.out.print("Five dice rolls:");
for (int i = 0; i < 5; i++) {
int roll = random.nextInt(6) + 1; // nextInt(6) gives 0 to 5, so shift up by one
System.out.print(" " + roll);
}
System.out.println();
int min = 50, max = 60;
int inRange = random.nextInt(max - min + 1) + min; // inclusive range 50 to 60
System.out.println("Between 50 and 60: " + inRange);
System.out.println("Coin flip: " + (random.nextBoolean() ? "Heads" : "Tails"));
}
}Output
Core Logic
nextInt(bound) returns a value from 0 up to bound - 1, so any inclusive range comes from choosing the bound and then adding an offset.
- 1
new Random(7)fixes the seed, so the output on this page is reproducible;new Random()would give different numbers each run. - 2
nextInt(6) + 1turns the range 0–5 into a die's 1–6. - 3
nextInt(max - min + 1) + mingives any range frommintomax, both ends included. - 4
nextBoolean()returns true or false with equal chance, used here for heads or tails.
nextInt(11) gives 0–10, and adding 50 shifts that to 50–60.Key Point: Forgetting the + 1 in max - min + 1 is the classic off-by-one bug — the maximum value would never be produced.
Key Concepts
Approach 2: Random Decimals in a Range
import java.util.Random;
public class RandomNumbersDecimal {
public static void main(String[] args) {
Random random = new Random(7);
double min = 1.5, max = 4.5;
for (int i = 0; i < 3; i++) {
double value = min + random.nextDouble() * (max - min); // nextDouble is in [0.0, 1.0)
System.out.printf("%.2f%n", value);
}
}
}
Output
Core Logic
nextDouble() returns a value from 0.0 up to (but not including) 1.0, which can be stretched and shifted onto any decimal range.
- 1Multiplying by
(max - min)stretches the 0–1 range to the width of the target range. - 2Adding
minshifts it to start at the right place. - 3
printf("%.2f%n")shows each value to two decimal places.
nextDouble() result of 0.73 becomes 1.5 + 0.73 × 3 = 3.69.Key Point: Math.random() does the same as nextDouble() but can't be seeded — use a Random object when you need repeatable results, such as in tests.
Key Concepts
Interview Questions
What's the difference between Random and Math.random()?
Math.random() returns a double in [0, 1) from a shared generator. Random offers nextInt, nextBoolean and seeding for repeatable results.
Which class should be used for passwords or tokens?
SecureRandom. Random is predictable and unsafe for security purposes.