Advertisement
Home Data Structure Arrays Random Pick from an Array

Random Pick from an Array

1
Advertisement

Title: Random Pick from an Array

In this guide, you’ll learn how to pick a random element from an array in Java using the java.util.Random class. This is a common requirement whenever you need unpredictable behavior – selecting a random winner, shuffling a quiz question, or sampling test data – and getting it right matters more than it looks.

We’ll build a small, reusable method for picking a random element, walk through exactly how the random index is generated, and then cover the mistakes, edge cases, and interview follow-ups that come up once you start using this pattern in real code.

Understanding the Problem

Given an array of elements, the goal is to select one element from it such that every element has an equal chance of being chosen. The array itself does not change; you are reading one position out of it based on a randomly generated index.

The core challenge is translating ‘pick randomly’ into a valid array index. Java’s Random class makes this easy with nextInt(bound), which returns an integer in the range [0, bound), exactly the range of valid indices for an array of length bound.

Approach / Algorithm Steps

  1. Check that the array is not null and not empty; there is nothing valid to pick from otherwise.
  2. Create one Random instance in the caller (for example, in main) rather than inside the picking method.
  3. Pass the shared Random instance into the picking method so every call reuses it instead of constructing a new one.
  4. Call random.nextInt(numbers.length) to generate a random index in the range [0, numbers.length).
  5. Use the generated index to read the element at that position in the array.
  6. Return the picked element to the caller.

Java Program

Java
import java.util.Random;

public class RandomPickFromArray {

    public static int pickRandomElement(int[] numbers, Random random) {
        if (numbers == null || numbers.length == 0) {
            throw new IllegalArgumentException("Array must not be null or empty");
        }
        int randomIndex = random.nextInt(numbers.length);
        return numbers[randomIndex];
    }

    public static void main(String[] args) {
        int[] numbers = {10, 20, 30, 40, 50};
        Random random = new Random();

        int picked = pickRandomElement(numbers, random);
        System.out.println("Randomly picked element: " + picked);
    }
}

Explanation of the Program

  • pickRandomElement guards against a null or empty array with an IllegalArgumentException, so a bad call fails loudly instead of returning garbage.
  • The Random instance is created once in main and passed into pickRandomElement, so repeated picks never pay the cost of constructing a new Random object.
  • random.nextInt(numbers.length) returns a value from 0 to numbers.length - 1, which is exactly the valid index range for the array.
  • numbers[randomIndex] reads the element at that position, and the result is returned to main.
  • main prints the picked element; running the program again will usually print a different value because Random is seeded from the system clock by default.

Step-by-Step Trace

For numbers = {10, 20, 30, 40, 50}, suppose pickRandomElement is called five times in a row using the same shared Random instance. The exact indices depend on the Random seed, but the mapping from index to value always works the same way:

CallnextInt(5) returnedrandomIndexnumbers[randomIndex] (picked)
12230
24450
30010
43340
51120

At the end of each call, randomIndex is an independent value drawn uniformly from [0, numbers.length), so picked is equally likely to be any of the five array elements, regardless of what previous calls returned.

Examples

Example 1: Picking from an Array of Strings

Random works the same way for any reference type, not just int arrays.

Java
String[] fruits = {"Apple", "Banana", "Cherry", "Date"};
Random random = new Random();

String pickedFruit = fruits[random.nextInt(fruits.length)];
System.out.println("Picked fruit: " + pickedFruit);
// Sample output: Picked fruit: Cherry

Example 2: Picking Several Times in a Loop

Reusing the same Random instance across repeated picks keeps every call independent and uniformly distributed.

Java
int[] scores = {55, 68, 72, 81, 95};
Random random = new Random();

for (int i = 0; i < 3; i++) {
    int picked = scores[random.nextInt(scores.length)];
    System.out.println("Pick " + (i + 1) + ": " + picked);
}
// Sample output:
// Pick 1: 81
// Pick 2: 55
// Pick 3: 95

Example 3: Using a Fixed Seed for Reproducible Picks

Passing a seed to Random makes the sequence of picks deterministic, which is useful in unit tests.

Java
int[] values = {100, 200, 300};
Random random = new Random(42);

int picked = values[random.nextInt(values.length)];
System.out.println("Picked value: " + picked);
// Output is always the same across runs because the seed is fixed

Common Mistakes to Avoid

These are the mistakes that show up most often when developers first wire up random picking in Java.

  • Creating a new Random instance inside a loop – calling new Random() on every iteration wastes objects and, if several instances are created within the same millisecond, can produce correlated sequences. Create one Random instance and reuse it.
  • Using Math.random() * numbers.length and casting to int – floating point rounding at the edge can produce an index equal to numbers.length, throwing ArrayIndexOutOfBoundsException. Use random.nextInt(numbers.length) instead; it never returns an out-of-range value.
  • Forgetting to check for an empty array – calling random.nextInt(0) throws IllegalArgumentException: bound must be positive. Validate numbers.length > 0 before picking.
  • Assuming nextInt(bound) can return bound itself – nextInt(numbers.length) only ever returns 0 through numbers.length - 1. Treat the upper bound as exclusive, matching normal array indexing.
  • Expecting the same picked value on every run – without a fixed seed, each execution produces an unpredictable result. Pass a fixed seed to Random only when reproducibility is required, such as in tests.

Edge Cases to Test

Walk through these input shapes before calling the problem solved.

  • Empty array
  • Single-element array
  • Array of duplicate elements
  • Very large array
  • Null array reference
  • Negative numbers in the array
  • Array of objects instead of primitives
  • Picking concurrently from multiple threads

Additional Considerations

Picking a random element this way runs in O(1) time and uses O(1) extra space; nextInt does a constant amount of work regardless of the array’s length.

java.util.Random is thread-safe, but multiple threads calling nextInt on the same instance contend for an internal seed update, which hurts throughput under heavy concurrency. Prefer java.util.concurrent.ThreadLocalRandom.current() when picking happens from multiple threads.

nextInt(bound) is specified to return values uniformly distributed over [0, bound), so every element of the array has exactly a 1 / numbers.length chance of being picked on each call, independent of prior calls.

Interview Follow-up Questions

An interviewer rarely stops at the base version; these are the natural next questions.

  • What if you need to pick a random element without repeating any previously picked one? – shuffle a copy of the array (Fisher-Yates or Collections.shuffle) and consume it from the front, or swap each picked element with the last unpicked one and shrink the logical bound.
  • What if the array is given as a stream of unknown length and you can only read it once? – apply reservoir sampling; keep the current pick and replace it with the i-th incoming element with probability 1/i.
  • What if you need to pick K random elements without duplicates? – extend reservoir sampling to a reservoir of size K, or run a partial Fisher-Yates shuffle and take the first K entries.
  • What if multiple threads call the pick method concurrently? – swap java.util.Random for java.util.concurrent.ThreadLocalRandom.current() to avoid contention on a shared seed.
  • What if elements must be picked with unequal, weighted probabilities? – build a prefix-sum array of weights and binary-search a random value in [0, totalWeight).

Conclusion

Picking a random element from an array comes down to one idea: let Random.nextInt(length) generate a valid index, then read the array at that index. Once that core idea is solid, the variations – picking without repeats, picking from a stream, picking several at once, weighted picking – are all extensions of the same technique, not new problems.

Try adapting pickRandomElement to work with a List<T> using generics, or combine it with the reservoir sampling idea from the follow-up questions. You can learn more about array-based techniques in the Arrays category: https://dailyjavaconcept.com/category/arrays/