Today we’ll learn ways in which we can generate a random integer in a given range – minValue to maxValue, both inclusive in Java. It is a common requirement we come across while writing some algorithmic solutions. So let’s get started!
A traditional solution to generate a random integer in the range of minValue – maxValue ( both inclusive) would be using Math.random() method:
public int generateRandomInteger(int minValue, int maxValue) { return (int) (Math.random() * (maxValue - minValue + 1)) + minValue; }
Note that Math.random() returns a random double value in range – 0.0 to 1.0 (1.0 exclusive).
Here (maxValue – minValue + 1) is the entire range length. Let’s work our way with an example :
Example: Generate a random integer in range 4 – 10(both inclusive).
Lower Bound Case : Math.random() produced 0.1 for our case. Then,
Generated Random Integer = (int)(0.1 * (10-4+1)) + 4 = (int)0.7 + 4 = 0 + 4 = 4
Upper Bound Case : Math.random() produced 0.9 for our case. Then,
Generated Random Integer = (int)(0.9 * (10-4+1)) + 4 = (int)6.3 + 4 = 6 + 4 = 10
java.util.Random.nextInt(int maxValue) method generates a pseudorandom number in range 0 – maxValue, maxValue exclusive. So to generate a random integer in given range(both inclusive), we’ll write:
public int generateRandomInteger(int minValue, int maxValue) { Random rand = new Random(); return rand.nextInt(maxValue - minValue + 1) + minValue; }
Depending on the criticality of the requirement, it is advisable to have good understanding of pseudorandom number generation and passing good seed values to Random class constructor.
Java 7 onwards, it is advisable to use java.util.concurrent.ThreadLocalRandom over java.util.Random class. The code is clean and simple :
public int generateRandomInteger(int minValue, int maxValue) { return ThreadLocalRandom.current().nextInt(minValue, maxValue + 1); }
Note that we have used maxValue+1 to make sure maxValue is included in the range.
Apache Commons Library provides a method RandomUtils.nextInt(int maxValue) which generates a random integer in range 0 to maxValue, maxValue exclusive. So, we can choose to use it for our solution as well :
public int generateRandomInteger(int minValue, int maxValue) { return RandomUtils.nextInt(maxValue - minValue + 1) + minValue; }
In this article, we have learned ways to generate a random integer in Java within a specified range, both edges inclusive.
So the next time we are working with an algorithm which requires some input randomization, we are good to go. Cheers!