Generate Random Integers between Specified Range in Java

In this post, we will see how to generate random integers between specified range in Java.


1. Random Class

We can use Random.nextInt() method that returns a pseudorandomly generated int value between 0 (inclusive) and the specified value (exclusive).

Below code uses the expression nextInt(max - min + 1) + min to generate a random integer between min and max. It works as nextInt(max - min + 1) generates a random integer between 0 to (max - min) and adding min to it will result in random integer between min to max.


Download   Run Code

In Java 8 and above, we can use ints() method provided by the Random class which returns an unlimited stream of pseudo-random int values within the specified range as shown below:


Download   Run Code


2. Math.random()

We can also use Math.random() that internally uses Random.nextDouble(), and returns a pseudo-random double within the range [0.0, 1.0).

The following code uses the below expression to generate random integer between min and max.

It works as Math.random() generates a random double value in the range [0.0, 1.0). When we multiply it by ((max - min) + 1), the lower limit remains 0 but the upper limit becomes (max - min, max - min + 1). Now on casting it with an int, the range becomes [0, max - min] and on adding min, the range becomes [min, max].


Download   Run Code


3. Java 7 – ThreadLocalRandom Class

Another option is to use ThreadLocalRandom class which is a subclass of java.util.Random class for multi-threaded environments. This class was introduced in Java 7.

The use of this class is recommended over having shared Random objects in concurrent programs. ThreadLocalRandom offers better performance as a random integer is now generated locally within the same thread.


Download   Run Code


4. SecureRandom Class

We can also use SecureRandom class, a subclass of java.util.Random class, which provides a cryptographically strong random integer generator.


Download   Run Code


5. Apache Commons

With Apache Commons, we can construct a RandomDataGenerator instance using the supplied RandomGenerator or default random generator as the source of randomness. RandomData can also be used but it is deprecated now.



Thanks for reading.

Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂

Leave a Reply

Notify of