How to Generate Random Integers With a Range in Java


Java comes with many different ways to generate random integers, even if you need to specify a lower and upper bound to constrain your required value for.

Option 1 – ThreadLocalRandom

Specify the min and max values:

import java.util.concurrent.ThreadLocalRandom;

int randomNum = ThreadLocalRandom.current().nextInt(min, max + 1);

Option 2 – Random

Between `` (inclusive) and the specified value (exclusive):

import java.util.Random;

Random rn = new Random();
int range = maximum - minimum + 1;
int randomNum =  rn.nextInt(range) + minimum;

Option 3 – Multiple values

import java.util.Random;

Random r = new Random();
int[] fiveRandomNumbers = r.ints(5, 0, 11).toArray();
int randomNumber = r.ints(1, 0, 11).findFirst().getAsInt();