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();
rand.nextInt();
rand.nextInt(100);

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 java.security.SecureRandom 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. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Current day month ye@r *