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. 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>

Subscribe to JournalDev Newsletter
Get the FREE access to JournalDev Newsletter and Free PDF eBooks
*No Spam Guaranteed. By entering your email address, you agree also subscribing to our newsletter.
Oops! - Something went wrong.
Database Hackers Handbook worth $37 FREE Download Now
'Java Video Tutorial Series' at 83% Discount - Coupon Code '10ACHIEVE' Enroll Now
Advertisment ad adsense adlogger