Java - Get a random number from a range

By xngo on February 23, 2019

In Java, writing a function to get a random number from a range is not that hard. It is just a matter of finding the correct function to cleanly convert from Double to Integer. A lot of time is wasted to find how to do that as I'm not familiar with the functions they offer. I simply want to put this out here so that later, if needed, I can get it from here.

Get a random integer from a range

Math.random() returns a random decimal number between 0 and 1. You can treat it as percentage. Multiple that random decimal number to the range between a and b. Then, convert it to an integer. And, finally, add it to a.

Here is the code:

public static int getRandomInt(int a, int b){
 
    int range = b-a;
    double rndDouble = Math.random()*range;
 
    return Double.valueOf(rndDouble).intValue()+a;
}

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.