Generate Random Number within a range in Java

Sometimes we need to generate random numbers in Java programs, for example a dice game or to generate random key id for encryption etc.

java.util.Random class can be used to create random numbers. It provides several methods to generate random integer.

Random rand = new Random();

Second line returns a random int whereas third line returns a random int between 0 (inclusive) and 100 (exclusive). However sometimes we need to generate random int within a range.

public static int getRandomNumberWithin(int lower, int upper) {
        Random rand = new Random();
        int randomNumber = rand.nextInt(upper - lower) + lower;
        if(randomNumber == lower) {
            return lower + 1;
        else {
            return randomNumber;


Above function will return random number within the given range, note that lower and upper both are exclusive.

Sometimes we need to generate random number that are more secure, in that case we can use class. This class is cryptographically strong random number generator (RNG). However it’s slow in processing, so depending on your application requirements, you should decide which one to use.


Leave a Reply

Your email address will not be published. For posting CODE wrap them inside <pre class="prettyprint"></pre>. Required fields are marked *