Generate Random Numbers in Java

In this post, we will see how to generate random numbers between 0 to n, both inclusive, in Java using Random class, Math.random(), ThreadLocalRandom class, SecureRandom class, and Apache Commons.


1. Random.nextInt()

We can use nextInt() provided by Random class that returns a pseudorandomly generated int value in the specified range. The value is uniformly distributed between 0 and one minus the specified value.


Download   Run Code


2. Math.random()

Another option is to use Math.random() that returns a pseudorandomly chosen double value greater than or equal to 0.0 and less than 1.0. It internally uses Random.nextDouble() and requires about twice time for processing.

Below example uses the expression (int)(Math.random() * (n + 1)) to generate random number between 0 to n. It works as Math.random() generates a random double value in the range [0.0, 1.0). When we multiply it by n + 1, the lower limit remains 0 but the upper limit becomes in range (n, n + 1). Now on casting it with an int, the range becomes [0, n].


Download   Run Code


3. Java 7 – ThreadLocalRandom Class

We can use ThreadLocalRandom class in Java 7 or later which is a subclass of java.util.Random class for multi-threaded environments.

The use of this class rather than shared Random objects in concurrent programs will typically result in better performance as a random number is now generated locally in current thread and this will reduce the conflicts and the overhead. Also, now we don’t need to explicitly initialize a java.util.Random instance.


Download   Run Code


4. Java 8 – Random.ints()

Java 8 introduced several new methods to the Random class which generates a stream of pseudorandom values. One such method is ints() that returns an unlimited stream of pseudorandom int values within the specified range.


Download   Run Code


5. SecureRandom Class

We can also use SecureRandom class which is a subclass of java.util.Random class and provides a cryptographically strong random number generator.


Download   Run Code


6. Apache Commons

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



Exercise: Extend the solution to generate random integers between specified range.

1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5.00 out of 5)


Thanks for reading.

Please use our online compiler to post code in comments. To contribute, get in touch with us.
Like us? Please spread the word and help us grow. Happy coding 🙂

Leave a Reply

Notify of