1. Overview

Generating random numbers is a common programming task primarily used in simulation, testing, and games. In this tutorial, we’ll cover multiple ways of filling the content of an array with random numbers generated using Pseudo-Random Number Generators.

2. Using an Iterative Approach

Among the various available approaches, we can iteratively fill the content of an array with random numbers using the methods provided by the Random, SecureRandom, and ThreadLocalRandom classes, which are suitable for different scenarios. These classes generate pseudo-random numbers in Java and have methods like nextInt(), nextDouble(), and others.

Let’s look at an example of how we can fill an array using the nextInt() method:

int LOWER_BOUND = 1;
int UPPER_BOUND = 100;
int ARRAY_SIZE = 10;
int[] arr = new int[ARRAY_SIZE];
// random number generator
Random random = new Random();
/ iterate and fill
for (int i = 0; i < arr.length; i++) {
    arr[i] = random.nextInt(LOWER_BOUND, UPPER_BOUND);
}

System.out.println(Arrays.toString(arr));

The code above randomly produces the  following output:

[31, 2, 19, 14, 93, 31, 78, 46, 9, 46]

We defined an array of ARRAY_SIZE elements and filled it with random numbers within the range LOWER_BOUND and UPPER_BOUND (exclusive). We’ll be maintaining the same size and boundary throughout subsequent code examples.

In addition to the classes mentioned, we can use the Math.random() static method to achieve the same goal. Math.random() returns a pseudo-random double within the range 0.0 (inclusive) to 1.0 (exclusive):

int[] arr = new int[ARRAY_SIZE];
// iterate and fill
for (int i = 0; i < arr.length; i++) {
    arr[i] = (int) (Math.random() * (UPPER_BOUND - LOWER_BOUND)) + LOWER_BOUND;
}

System.out.println(Arrays.toString(arr));

Let’s see what the console displays after executing the code:

[78, 9, 46, 39, 78, 90, 46, 79, 51, 25]

Whichever class and method we choose solely depends on the application’s requirements.

3. Using Java Streams

We can generate random numbers using the ints(), longs(), and doubles() methods added to the pseudo-random number classes in Java 8 and above.  These methods enable the generation of streams of random numbers and allow for the efficient creation of random integers, long values, and doubles efficiently.

Let’s demonstrate the above with an example using the ints() method:

// random number generator
Random random = new Random();
// fill with ints method
int[] arr = random.ints(ARRAY_SIZE, LOWER_BOUND, UPPER_BOUND).toArray();

System.out.println(Arrays.toString(arr));

Let’s see what output the code yields:

[73, 75, 50, 92, 8, 6, 12, 41, 40, 85]

The above shows how these methods make it easy to populate an array’s content without using a loop.

4. Using the Arrays.setAll() Method

Another way to fill the content of an array with default values is by using the static *Arrays.*setAll() method, which sets all elements of the specified array using a generator function. This method can be combined with random number generators to fill an array with random numbers cleanly and concisely. The method can be used with any pseudo-random number generator or any other function we wish to use.

Let’s see this in action using the SecureRandom number class:

int[] arr = new int[ARRAY_SIZE];

// fill content
Arrays.setAll(arr, r -> new SecureRandom().nextInt(LOWER_BOUND, UPPER_BOUND));

System.out.println(Arrays.toString(arr));

Upon running the above code, we’ll get the following random numbers:

[5, 30, 88, 28, 20, 86, 6, 74, 31, 80]

5. Using a Seed to Generate Random Numbers

In some situations, we want to generate the same sequence of random numbers or avoid generating the same sequences (default behavior) every time. The Random and SecureRandom class permits setting a seed value either at the point of initialization or later. In contrast, the ThreadLocalRandom class does not support setting a seed directly for the sake of performance enhancement.

Let’s see with an example how this works:

// Produce identical elements repeatedly
int[] arr = new Random(12345).ints(ARRAY_SIZE, LOWER_BOUND, UPPER_BOUND).toArray();

int[] arr2 = new Random(12345).ints(ARRAY_SIZE, LOWER_BOUND, UPPER_BOUND).toArray();

System.out.printf("Arr: %s%n", Arrays.toString(arr));
System.out.printf("Arr2: %s%n", Arrays.toString(arr2));

// using different seeds
int[] arr3 = new Random(54321).ints(ARRAY_SIZE, LOWER_BOUND, UPPER_BOUND).toArray();

System.out.printf("%nArr2: %s%n", Arrays.toString(arr2));
System.out.printf("Arr3: %s%n", Arrays.toString(arr3));

Let’s see what the example above produces after execution:

Arr: [95, 95, 7, 55, 68, 77, 8, 73, 26, 88]
Arr2: [95, 95, 7, 55, 68, 77, 8, 73, 26, 88]

Arr2: [95, 95, 7, 55, 68, 77, 8, 73, 26, 88]
Arr3: [22, 20, 39, 49, 86, 3, 83, 46, 98, 88]

From the example above, it’s clear that setting the same seed value for arr and arr2 allows us to regenerate identical sequences of numbers. This demonstrates how seeding provides consistency and repeatability in random number generation.

If we don’t set any seed value or we set different seed values always, we get a different sequence, just as with the arr2 and arr3. This is the default behavior if no seed value is set.

Note: In cases where no seed or a different seed value is provided, you might get different results from the ones shown in the article because of randomness. 

6. Conclusion

In this article, we’ve explored various ways to fill an array with random numbers using random number generators in Java. Each pseudo-random number generator class has its advantages and disadvantages.

Understanding the significance of seeds can help you generate repeatable sequences when needed, which can be invaluable for debugging, simulation, and testing and can be another layer of utility to the random number generation toolkit.

Complete code examples are available over on GitHub.