Java: Generating Random Integers & Choosing Random List Items

java random numbers random list item selection

Generating random integers in Java can be useful for a myriad of applications. While pseudorandom generators aren’t appropriate for security-based applications they are still widely applicable for casual use (video games, simulations, testing, etc.)

Generating random integers can be useful for not only creating a simulation or testing data but also for use in selecting random items from a collection. Or, if you’re feeling really squirrelly, selecting a random item from a random collection! To get started, one must first understand how to generate random integers in Java.

Note: Code from this post is available on GitHub

Generating Random Integer Values in Java

Random’s NextInt Method

java.util.Random.nextInt

Java’s Random package has quite a slew of randomization options. Among them: the nextInt() method. From the official Oracle Documentation:

Returns the next pseudorandom, uniformly distributed int value from this random number generator’s sequence.

This will return a random integer value within the range of all possible (signed) integer values: -2,147,483,648 to 2,147,483,647 (2-31 to 231 – 1). To learn more about the possible values of Java datatypes read the official Oracle article. That’s great, but what about those times one needs a random integer within a specific range of values? The nextInt(int bound) method has you covered!

Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive), drawn from this random number generator’s sequence.

Note the “exclusive” part of that documentation. That means the upper bound will not be included as an option. This is common among programming languages but important to keep in mind.

Examples

Knowing how the Random.nextInt() method works is one thing, but knowing how to apply it is another. Below are several examples of how this Java built-in can help address common programming tasks. For all tasks: import java.util.Random;

Generating a Random Integer

int randomInteger= new Random().nextInt();

Generating a Random Integer Between 0 and 10

int randomInteger = new Random().nextInt(10);

Generate a Random Integer in Range (Exclusive Upper Bounds)

// Define min/max
int min = 5;
int max = 10;

// Generates the random integer
int randomInteger = new Random().nextInt((max - min)) + min;

This one deserves a bit of quick discussion to understand on a conceptual level. It can be broken down into two parts:

  1. Generate a number in the range of 0 to  (max - min).
  2. Map that number to the range of min to max.

This two-step process can be described as first getting a value from the correct number of possibilities and then adding back the minimum to ensure the value is from the correct range of values. Consider the illustration below:

java random integer in range
The first step in selecting a number in a random range is to generate a number from the appropriate number of possible values followed by mapping to the correct range of possible values.

This provides an easy way to produce a random integer value within a specified range. For example, a random number between 1 and 10; a random number between 50 and 100; a random nu… you get the idea.

Selecting Random Collection Items

Armed with the know-how to generate random numbers, one can quickly realize the application in selecting random elements from existing collections. The code below selects a random element from an array of integers and prints the result to the console:

// Declare and init an array of numbers
int[] numbers = new int[]{1, 2, 3, 5, 8, 13};

// Use length of list to generate random number in range of list length
int randomNumber = new Random().nextInt(numbers.length);

// Use random number as index into array
int choice = numbers[randomNumber];

// Print to console
System.out.println(choice);

Each time this program runs, it should print an element from the array, which each element having P(1/6) of being chosen.

Creating an Array of Random Elements

Extending the combinatorial power of collection and random numbers, let’s see how to generate a list of n-many integers each random chosen from within a min-max range.

// declare & initialize numbers collection, random generator
int length = 10;
int[] numbers = new int[length];
Random rand = new Random();
        
// Define range of values
int min = 0;
int max = 100;

// Generate random number for each element in array
for(int i = 0; i < length; i++){
    numbers[i] = rand.nextInt(max-min) + min;
    }

// Print array of random numbers to console as string
System.out.println(Arrays.toString(numbers));

When I rand the above instructions, the following was printed to console:

[47, 28, 46, 38, 28, 41, 25, 1, 9, 96]

Discussion

The need for pseudo-random integers is common. Selecting random list items, generating random ranges, and profiling certain performance considerations are applications for such data. Languages like Python seem to accommodate these features with a little more native feel, but Java has all the tools one needs to generate pseudo-random numbers.

Zαck West
Full-Stack Software Engineer with 10+ years of experience. Expertise in developing distributed systems, implementing object-oriented models with a focus on semantic clarity, driving development with TDD, enhancing interfaces through thoughtful visual design, and developing deep learning agents.