Java program to generate a random number from an array


In this article, we will learn how to generate a random number from an array of integers in Java by using Random class. The Random class provides methods to generate random numbers, and we will use the nextInt(int bound) method to get a random index within the bounds of our array length.

Problem Statement

Given an array of integers, we need to randomly select and display one element from the array using java.

Input

arr = { 10, 30, 45, 60, 78, 99, 120, 140, 180, 200};

Output

Random number from the array = 30 

Steps to Generate a Random Number from an Array

The following are the steps to generate random number from an array:

  • Step 1: Initialize the Array.
  • Step 2: Create a random object.
  • Step 3: Generate a random index.
  • Step 4: Retrieve and print the random element.

Example

import java.util.Random;
public class Demo {
    public static void main(String... args) {
    int[] arr = new int[] { 10, 30, 45, 60, 78, 99, 120, 140, 180, 200};
    System.out.print("Random number from the array = "+arr[new Random().nextInt(arr.length)]);
    }
}

Output

Random number from the array = 45

Code Explanation

Initially we will import the random class then we will define a public class Demo with the main method where the execution starts. We create and initialize an array named arr with integer elements.

int[] arr = new int[] { 10, 30, 45, 60, 78, 99, 120, 140, 180, 200};

Now, we will get a random number from array using new Random() which creates a new instance of the random class. The nextInt(arr.length) generates a random integer from 0 to the length of the array. In the array, arr.length is 10, so nextInt(10) will generate a random integer between 0 and 9.

arr[new Random().nextInt(arr.length)]

In the above code, it uses the randomly generated index to access an element in the arr array. And we will print the selected random element from the array to the console.

System.out.print("Random number from the array = " + arr[new Random().nextInt(arr.length)]);

Updated on: 02-Jul-2024

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements