java.util.Random Example

January 31, 2021 |

Generating Random Number in Java

This article summarizes different ways to use the Random() class in java to generate bounded or unbounded random numbers. It also shows another important feature of the class that is using seed to generate same set of random numbers.
java.util.Random used used to generate bounded or unbounded random numbers. It supports specifying a seed which is used to set the internal state of the pseudorandom number generator. Random(): creates new random generator Random(long seed): creates new random generator using specified seed
Unbounded generate 5 random numbers
Following code prints 5 random numbers unbounded without any seed
``````public static void generateRadom() {
System.out.println("\nPrinting 10 Random Numbers");
Random generator = new Random();
for (int i = 0; i < 5; i++) {
System.out.print(generator.nextInt() + " ");
}
}``````
Invocation 1
Printing 5 Random Numbers -1937915077 75383412 -901884443 1725835531 1371480362
Invocation 2
Printing 5 Random Numbers -1261854044 328673857 -1787159304 446964878 -283294822
Notice that in both the invocations the generated numbers are different. This is because we have not set any seed in the Random Class.
Random Bounded Number
Following method will generate 5 random numbers between 0 and 99
``````public static void generateRadomBounded() {
System.out.println("\nPrinting 5 Random Numbers Between 0 and 99");
Random generator = new Random();
for (int i = 0; i < 5; i++) {
System.out.print(generator.nextInt(100) + " ");
}
}``````
Invocation 1
Printing 5 Random Numbers Between 0 and 99 25 95 13 60 67
Invocation 2
Printing 5 Random Numbers Between 0 and 99 17 10 21 96 15
Generate Random number bounded with a seed
Bellow function will generate bounded 5 random numbers but since we are setting a seed, if the seed is same on multiple invocation then each invocation will generate the same set of random numbers.
``````public static void generateRadomWithSeed(long seed) {
System.out.println("\nPrinting 5 Random Numbers Between 0 and 99 with seed");
Random generator = new Random(seed);
for (int i = 0; i < 5; i++) {
System.out.print(generator.nextInt(100) + " ");
}
}``````
Invocation 1
Printing 5 Random Numbers Between 0 and 99 with seed 4 62 52 3 58 67
Invocation 2
Printing 5 Random Numbers Between 0 and 99 with seed 4 62 52 3 58 67
Summary
• If we want to generate the same set of random numbers, we can set seed.
• Test cases can use seed to make sure it gets same set of random numbers.
• We can have bounded or unbounded random numbers.