Java Program to generate a random number from an array

Java 8Object Oriented ProgrammingProgramming

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
raja
Published on 23-Apr-2019 09:03:29
Advertisements