- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
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
Advertisements
To Continue Learning Please Login
Login with Google