JavaEssential standard classesStandard classes for computations

Random

Sometimes you need to get a random number or another value. It may be useful for testing purposes or using as an initial value in some kind of algorithms or in a game. For this purpose, Java provides the Random class that represents a generator of pseudorandom sequences. These sequences are not truly random, because it is completely determined by an initial value, called seed. Although such generators are important in practice for their speed in number generation and their reproducibility.[


Creating a pseudorandom generator

The class Random can be used to generate random values of different types, such as int, long, double, and even boolean. We will consider how to use it for numbers.

To start using this class, first, we need to import it:

import java.util.Random;

Then we have two constructors to create an object of this class:

  • Random() creates a new pseudorandom generator and sets the seed of the generator to a value very likely to be distinct from any other invocation of this constructor:
Random random = new Random();

  • Random(long seed) create a new pseudorandom generator with the specified initial value of the internal state of it:
Random random = new Random(100000);

The basic methods

After we have created a generator, we may invoke one of the following methods on the object:
  • int nextInt() returns a pseudorandom value of the int type;
  • int nextInt(int n) returns a pseudorandom value of int type in the range of from 0 (inclusive) to n (exclusive);
  • long nextLong() returns a pseudorandom value of long type;
  • double nextDouble() returns a pseudorandom value of double type between 0.0 and 1.0;
  • void nextBytes(byte[] bytes) generates random bytes and places them into a user-supplied byte array.
All the listen methods produce uniformly distributed values.

Here is an example below:

Random random = new Random();
System.out.println(random.nextInt(5)); // it may print 0, 1, 2, 4

If we start this code multiple times, the result is different (but sometimes may be the same).

If we need to reproduce the same sequence of random numbers, we may specify a seed to the constructor:

Random random = new Random(100000);
System.out.println(random.nextInt(5)); // it may print 0, 1, 2, 4
System.out.println(random.nextInt(5)); // it may print 0, 1, 2, 4

After multiple starts, we will always get the same numbers in the output.

It is also possible to generate gaussian distributed pseudorandom double numbers invoking the nextGaussian() method. This distribution may be necessary for some statistics and machine learning applications.

An example: printing pseudorandom numbers

Suppose we need a program that prints the specified number of pseudorandom integers from the given range (inclusive both borders). To write this program we should understand how to generate numbers in a range, because there is no such method.

The first thing, we will get the low border + 1 to include it in the range.
The second thing, we should invoke the nextInt(int n) method and shifts the generated value to the right.

Here is an example of how the solution may look.

import java.util.*;

public class RandomNumbersDemo {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        int n = scanner.nextInt();
        int from = scanner.nextInt();
        int to = scanner.nextInt() + 1;

        Random random = new Random();

        for (int i = 0; i < n; i++) {
            System.out.println(random.nextInt(to - from) + from);
        }
    }
}

Suppose we have to generate exactly 10 numbers in the range from 20 to 30 (inclusive):

10 20 30

An output example:

24
25
26
30
20
28
28
28
21
22

As you may see, in practice work with the Random class is simple enough.
4 learners liked this piece of theory. 0 didn't like it. What about you?
Report a typo