Generate a random array of integers in Java


In order to generate random array of integers in Java, we use the nextInt() method of the java.util.Random class. This returns the next random integer value from this random number generator sequence.

Declaration − The java.util.Random.nextInt() method is declared as follows −

public int nextInt()

Let us see a program to generate a random array of integers in Java −

Example

 Live Demo

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

Note − 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();

Updated on: 12-Sep-2023

31K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements