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.

About Pankaj

If you have come this far, it means that you liked what you are reading. Why not reach little more and connect with me directly on Google Plus, Facebook or Twitter. I would love to hear your thoughts and opinions on my articles directly.

Recently I started creating video tutorials too, so do check out my videos on Youtube.

I read a lot of books, below is the one I am currently reading.

Below are some of the recommended books in different technologies.

Some of the video tutorials on Udemy I would recommend are;

Join our email newsletter to get promo codes for almost 90% discount on these courses, and yes you will get a lot of free eBooks too, absolutely Free.

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=""> <s> <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.