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:

1
2
3
import java.util.concurrent.ThreadLocalRandom;

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

Option 2 – Random

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

1
2
3
4
5
import java.util.Random;

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

Option 3 – Multiple values

1
2
3
4
5
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();