Java Program to Generate a Random Number
Random numbers are used in games, simulations, test data and many other programs. Java offers three common ways to generate them:
- the
java.util.Randomclass, - the
Math.random()method, - the
java.util.concurrent.ThreadLocalRandomclass.
Because the numbers are random, the output on this page will be different every time you run the programs.
1. Random Numbers Using the Random Class
Create a Random object and call methods such as nextInt(), nextDouble() or nextBoolean(). nextInt(bound) returns a number from 0 up to, but not including, bound, so nextInt(100) + 1 gives a number from 1 to 100.
import java.util.Random;
public class RandomNumbers {
public static void main(String[] args) {
Random random = new Random();
System.out.println("5 random numbers from 1 to 100:");
for (int i = 0; i < 5; i++) {
System.out.println(random.nextInt(100) + 1);
}
System.out.println("Random double: " + random.nextDouble());
System.out.println("Random boolean: " + random.nextBoolean());
}
}
5 random numbers from 1 to 100: 45 1 67 67 19 Random double: 0.5555215832659274 Random boolean: true
2. Random Numbers Using Math.random()
Math.random() returns a double greater than or equal to 0.0 and less than 1.0. To get a whole number in the range min to max, multiply by the size of the range, cast to int and add min.
public class MathRandom {
public static void main(String[] args) {
double value = Math.random();
System.out.println("Random value: " + value);
int min = 1, max = 6;
int dice = (int) (Math.random() * (max - min + 1)) + min;
System.out.println("Dice roll: " + dice);
}
}
Random value: 0.31767054428967223 Dice roll: 3
3. Random Numbers Using ThreadLocalRandom
ThreadLocalRandom was added in Java 7. You do not create it with new; call ThreadLocalRandom.current() instead. Its nextInt(origin, bound) method takes a range directly, and it is the best choice in programs that use several threads.
import java.util.concurrent.ThreadLocalRandom;
public class ThreadLocalRandomDemo {
public static void main(String[] args) {
ThreadLocalRandom random = ThreadLocalRandom.current();
int number = random.nextInt(10, 21); // 10 to 20
double price = random.nextDouble(5.0, 50.0); // 5.0 to just under 50.0
long id = random.nextLong(1_000, 10_000); // 1000 to 9999
System.out.println("Random int (10-20): " + number);
System.out.printf("Random price: %.2f%n", price);
System.out.println("Random id: " + id);
}
}
Random int (10-20): 10 Random price: 11.14 Random id: 8196
4. Summary
new Random().nextInt(bound)returns a number from 0 tobound - 1.Math.random()returns adoublefrom 0.0 (inclusive) to 1.0 (exclusive); scale and cast it for a range.ThreadLocalRandom.current().nextInt(origin, bound)takes a range directly and suits multi-threaded code.- For passwords or security tokens, use
java.security.SecureRandominstead.