[Java] How to get a random element from an array?
I want to read a random element from the array, how can I do that in Java?
1 Answer
4 years ago by Eleven
Using java.util.Random we can generate a random number of length less than Array size and we can use that as index to pick a random element from array. Following code shows how to do that
import java.util.Random;
public class JavaArrays {
public static void main(String[] args) {
String[] colors = { "blue", "red", "green", "yellow" };
String randomColor = colors[new Random().nextInt(colors.length)];
System.out.println(randomColor);
}
}
Output:
blue
Try this code online here: https://onecompiler.com/java/3xmt8xa75
4 years ago by Karthik Divi