Core Java

Java – Generate Random Integer In Given Range

Introduction:

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!

Generating Random Integer:

  1. Using Math.random() :

    A traditional solution to generate a random integer in the range of minValuemaxValue ( both inclusive) would be using Math.random() method:

    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

  2. Using java.util.Random() :

    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:

    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.

  3. Using java.util.concurrent.ThreadLocalRandom :

    Java 7 onwards, it is advisable to use java.util.concurrent.ThreadLocalRandom over java.util.Random class. The code is clean and simple :

    Note that we have used maxValue+1 to make sure maxValue is included in the range.

  4. Apache Commons RandomUtils :

    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 :

Conclusion:

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!

Be the First to comment.

Leave a Comment

Your email address will not be published. Required fields are marked *