Home >Java >javaTutorial >How Can I Randomly Select an Element from an Array in Java?
Random Element Selection from an Array
In the realm of programming, selecting an element from an array at random is a common task. Understanding the array data structure and utilizing the Random class in Java are indispensable for achieving this goal.
Problem Statement:
Given an integer array, you seek a solution to randomly select one of its elements.
Solution:
To randomly pick an element from an array in Java:
Here's an example implementation:
import java.util.Random; public class RandomArrayElement { public static int getRandom(int[] array) { Random rnd = new Random(); int index = rnd.nextInt(array.length); return array[index]; } public static void main(String[] args) { int[] myArray = {1, 2, 3, 4, 5}; int randomElement = getRandom(myArray); System.out.println("Random element: " + randomElement); } }
This solution provides a simple and efficient way to select an element from an array in a truly random manner. By employing the Random class from the Java standard library, you can effectively mimic real-life scenarios where unpredictable outcomes are desired.
The above is the detailed content of How Can I Randomly Select an Element from an Array in Java?. For more information, please follow other related articles on the PHP Chinese website!