Generating Random Numbers In Java

A stream of pseudorandom numbers can be generated in Java using the java.util.Random class. To generate a random integer, an instance of this class can be created and the the nextInt(int n) method returned as shown below:

import java.util.Random;
public class RandomGenerator {
  public static void main(String args[]) {
    Random random = new Random();
    for (int i = 0; i < 5; i++) {
$ java RandomGenerator

In this code, the nextInt(int n) method takes a parameter as the upperbound for the random generated number. The random number is generated between 0 and n-1.

In addition to the nextInt(int n) methods, the Random class also has methods to return other primitives:

nextBoolean() – return the next random boolean nextFloat() – returns the next random float in the range 0.0 to 1.0 nextDouble() – returns the next double in the range 0.0 to 1.0

When generating random numbers, it is good practice to instantiate the Random class as few times as possible as this helps to ensure that random numbers do not follow a pattern. The above code example shows this where the Random class is instanced outside of the for loop.

The Java 8 documentation for the java.util.Random class is available here.

The java.util.Random class is not considered secure for cryptographic work. Instead, the class is recommended for these scenarios.

Although the java.util.Random class is thread safe, it may have performance issues when used in a multi-threaded environment. To overcome these issues, it is recommended to use the java.util.concurrent.ThreadLocalRandom class instead.