Java Program to generate a random number from an array


To generate a random number, create a Random object and use nextInt(). The same works for array as well.

Let us first create an array and add elements −

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

Now, get a random number from array by including the above mentioned array’s length under nextInt() −

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

Example

 Live Demo

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

Updated on: 30-Jul-2019

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements