
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Generate Random Number from an Array in Java
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 a random number from an array:
- First, we will import the Random class from java.util package.
- Initialize the Array.
- Create a random object.
- Generate a random index.
- Retrieve and print the random element.
Java program to generate a random number from an array
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)]);