How to Add Random Number to an Array in Java?
To generate an array of integers with random values the nextInt() method from the java.util.Random class is used. From the random number generator sequence, this method returns the next random integer value.
Assigning a Random Value to an Array
We can assign random values to an array by two approaches. If we do not pass any arguments to the nextInt() method, it will assign some arbitrary random value of the integer range in Java. If we pass some argument to the nextInt() method, it will generate numbers in the range between 0 to the argument passed.
Example 1: In this, we assign random values to an array without any range or between the minimum value of integers to the maximum value of integers (i.e. not passing arguments).
// Java Program to Add Random Number to an Array
import java.util.Random;
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int n = 5;
int[] arr = new int[n];
// Create a Random object
Random random = new Random();
// Assign random values to the array
for (int i = 0; i < n; i++) {
// Generate a random integer
// between INT_MIN and INT_MAX
arr[i] = random.nextInt();
}
// Print the array
System.out.println(Arrays.toString(arr));
}
}
Output
[-500572953, 583909042, -501070326, 290658844, 1861542031]
Example 2: In this, we are assigning random values to array with some specific range (i.e. passing arguments)
// Java Program to Add Random Number to an Array
import java.util.Random;
import java.util.*;
public class Main {
public static void main(String[] args) {
int n = 5;
int[] arr = new int[n];
// Create a Random object
Random random = new Random();
// Assign random values to the array
for (int i = 0; i < n; i++) {
// Generate a random integer
// between 0 and 99
arr[i] = random.nextInt(100);
}
// Print the array
System.out.println(Arrays.toString(arr));
}
}
Output
[19, 68, 84, 53, 26]