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 ye@r *

Subscribe to JournalDev Newsletter
Get the FREE access to Monthly Newsletter and Free PDF eBooks
*No Spam Guaranteed. By entering your email address, you agree also subscribing to our newsletter.
Oops! - Something went wrong.
Close
Today's Special: Java Persistence API PDF eBook Free Download Now
India's Independence Day Special: Java Persistence API eBook Free Download Now