The Random class is part of the java.util package and is used to generate pseudo-random numbers of different types: int, long, float, double, boolean, and Gaussian values.
- Based on a 48-bit seed using a linear congruential formula.
- Thread-safe only if externally synchronized.
- Can generate both bounded and unbounded values.
Commonly Used Methods

Simple Program: Lottery Generator
import java.util.Random;
public class SimpleRandomDemo {
public static void main(String[] args) {
Random random = new Random();
System.out.println("Your lucky lottery numbers are:");
for (int i = 0; i < 5; i++) {
int number = random.nextInt(100); // 0 to 99
System.out.println("Number " + (i + 1) + ": " + number);
}
}
}Problem Statement(Non-repeating Random Question Generator):
LotusJavaPrince is designing a quiz app that generates random question indices for each user. He wants to ensure that no question is repeated during a session. Use java.util.Random to generate non-repeating random indices from a list of questions.
import java.util.Random;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class QuizApp {
public static void main(String[] args) {
// Sample questions
String[] questions = {
"What is Java?",
"Explain polymorphism.",
"What is inheritance?",
"Define encapsulation.",
"What is abstraction?",
"What are exceptions in Java?",
"Difference between ArrayList and LinkedList?",
"Explain JVM, JRE, and JDK.",
"What is a constructor?",
"What is an interface?"
};
// Shuffle indices for random order without repetition
List<Integer> indices = new ArrayList<>();
for (int i = 0; i < questions.length; i++) {
indices.add(i);
}
// LotusJavaPrince wants randomness
Collections.shuffle(indices, new Random());
// Mahesh ensures no repetition
System.out.println("Randomized Question Set for the Session:");
for (int index : indices) {
System.out.println("- " + questions[index]);
}
}
}java.util.Random is ideal for basic random number generation.
- Use
nextInt(bound)for bounded numbers andnextGaussian()for statistical simulations. - For non-repeating sequences, combine
Randomwith structures likeListandCollections.shuffle(). - For cryptographic security, use
java.security.SecureRandominstead.
