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);
Code language: Java (java)

Option 2 – Random

Between 0 (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;
Code language: Java (java)

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();
Code language: Java (java)
Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments