Java Program to Generate Array of Random Integers

In this tutorial, we will be dealing with how to generate an array of random integers in a given range in Java.

In this tutorial, Emphasis will be on focusing on a random class of java.util package.

If you Don’t Know how to tackle with the above situation, then you are at the right destination because we will be going in-depth on the above-mentioned topic.

Java Program to Generate an Array of Random Integers

Initially, let us discuss the random class of java.util package. Random class is a part of the java. util package.

Therefore, the class provides us with several methods to generate random numbers of type integer, double, etc.

In this tutorial, we will be using the method nextInt() which returns the next integer value.

In contrast, it returns it from the random number generator sequence.

Firstly, we will be likewise creating a class named ‘CheckRandom’.java.Initially, we will be creating a Random class’s instance is created and we will be calling any of its random value generator methods.

Now, we will be creating an integer array.

Meanwhile, after creating an array, now loop till it’s the length,i.e, array’s length and take inputs through nextInt() method and assign accordingly to array one by one.

Now, we will be concluding on the method Array.toString, which returns a  string description of a specified array.

Basically, when we use this method, it simply in String converted formatted that is in [a,b,….] format.

Adjacent values or characters are separated by a comma(,), or other special characters.

The above-mentioned Array.toString takes an array as input.

It converts it into a formatted representation to be visible in a string converted format.

Below is Code for the above-mentioned problem:

import java.util.Arrays;
import java.util.Random;
import java.io.*;

public class CheckRandom 
{
  public static void main(String[] args) throws IOException
  {
    Random r = new Random();
   	int[] integers = new int[30];
        		for (int i = 0; i < integers.length; i++) 
    {
            	 		integers[i] = r.nextInt();
        		}
        		System.out.println(Arrays.toString(integers));
  }
}

In Contrast, After completion of the above program, we will be getting an array of random numbers generated in the array listing format that is in string formatted. To Conclude We get our desired result.

Below is the output of the above program:

how to generate an array of random integers in a given range in Java

Also read:

Leave a Reply

Your email address will not be published. Required fields are marked *