Create Arrays of Random Numbers in Java

The use of randomness is an important part of the configuration and evaluation of machine learning algorithms. From the random initialization of weights in an artificial neural network to the splitting of data into random train and test sets, to the random shuffling of a training dataset in stochastic gradient descent, generating random numbers and harnessing randomness is a required skill.

You may find yourself in need of an array of random numbers when working in JavaScript, such as when testing out a sorting algorithm. For example, an array of random numbers is useful when learning how to sort an array numerically, instead of lexicographically, in JavaScript.

Java has a "Random" class that lets you generate a random number you use to implement calculations in your Java source code. You use this library to generate a random number and insert the number into an array variable index. You can add one or several random numbers into your array variables, but Java does not guarantee that each number is unique.

In the following section, we will illustrate how to create arrays of random numbers in Java.

In the following example, we use the nextInt() method of the java.util.Random class. It will return the next random integer value from this random number generator sequence.

How to Create Arrays of Random Numbers in Java

// Declaration
public int nextInt()

Let us see an example to create a random array of integers in Java.

import java.util.Random;
public class Example {
   public static void main(String[] args) {
      Random rd = new Random(); // creating Random object
      int[] arr = new int[5];
      for (int i = 0; i < arr.length; i++) {
         arr[i] = rd.nextInt(); // storing random integers in an array
         System.out.println(arr[i]); // printing each array element
      }
   }
}

Output

-1848681552
39846826
858647196
1805220077
-360491047

Please note that the output might vary on Online Compilers. Here we use the nextInt() method in a loop to get a random integer for each element.

for (int i = 0; i < arr.length; i++)
arr[i] = rd.nextInt();


Leave a reply



Submit