Open In App

How to Add Random Number to an Array in Java?

Last Updated : 12 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

To 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.

Assign 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, then it will assign some arbitrary random value of integers range in Java and if we pass some argument to the nextInt() method then 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 ranging between the minimum value of integers to the maximum value of integers (i.e. not passing arguments).

Java




import java.util.Random;
import java.util.*;
  
public class RandomArrayValues {
    public static void main(String[] args) {
        // Declare the size of the array
        int n = 5;
  
        // Create an array
        int[] randomArray = 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
            randomArray[i] = random.nextInt(); 
        }
  
        // Print the array
        System.out.println("Random assigned value of Array are: ");
        for (int value : randomArray) {
            System.out.print(value+" ");
        }
    }
}


Output

Random assigned value of Array are: 
-170019732 2032213863 -1596767761 -1668938134 -210148393 





Example 2:

In this, we are assigning random values to array with some specific range (i.e. passing arguments)

Java




import java.util.Random;
import java.util.*;
  
public class RandomArrayValues {
    public static void main(String[] args) {
        // Declare the size of the array
        int n = 5;
  
        // Create an array
        int[] randomArray = 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
            randomArray[i] = random.nextInt(100); 
        }
  
        // Print the array
        System.out.println("Random assigned value of Array are: ");
        for (int value : randomArray) {
            System.out.print(value+" ");
        }
    }
}


Output

Random assigned value of Array are: 
4 51 85 25 33 







Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads