# How do I generate random integers within a specific range in Java?

+2654 votes
asked Dec 12, 2008

I am trying to generate a random `int`value with Java, but in a specific range.

For example:

My range is 5-10, meaning that 5 is the smallest possible value and 10 is the biggest. Any other number in between these numbers is possible to be a value, too.

In Java, there is a method `random()` in the `Math` class, which returns a `double` value between 0.0 and 1.0. In the class `Random` there is the method `nextInt(int n)`, which returns a random `int` value in the range of 0 (inclusive) and n (exclusive). I couldn't find a method, which returns a random integer value between two numbers.

I have tried the following things, but I still have problems: (minimum and maximum are the smallest and biggest numbers).

Solution 1:

``````randomNum = minimum + (int)(Math.random() * maximum);
``````

Problem:

`randomNum` can be bigger than `maximum`.

Solution 2:

``````Random rn = new Random();
int n = maximum - minimum + 1;
int i = rn.nextInt() % n;
randomNum =  minimum + i;
``````

Problem:

`randomNum` can be smaller than `minimum`.

How do I solve these problems?

I have tried also browsing through the archive and found:

But I couldn't solve the problem.

## 28 Answers

+2954 votes
answered Dec 12, 2008

In Java 1.7 or later, the standard way to do this is as follows:

``````import java.util.concurrent.ThreadLocalRandom;

// nextInt is normally exclusive of the top value,
// so add 1 to make it inclusive
int randomNum = ThreadLocalRandom.current().nextInt(min, max + 1);
``````

See the relevant JavaDoc. This approach has the advantage of not needing to explicitly initialize a java.util.Random instance, which can be a source of confusion and error if used inappropriately.

However, conversely there is no way to explicitly set the seed so it can be difficult to reproduce results in situations where that is useful such as testing or saving game states or similar. In those situations, the pre-Java 1.7 technique shown below can be used.

Before Java 1.7, the standard way to do this is as follows:

``````import java.util.Random;

/**
* Returns a pseudo-random number between min and max, inclusive.
* The difference between min and max can be at most
* <code>Integer.MAX_VALUE - 1</code>.
*
* @param min Minimum value
* @param max Maximum value.  Must be greater than min.
* @return Integer between min and max, inclusive.
* @see java.util.Random#nextInt(int)
*/
public static int randInt(int min, int max) {

// NOTE: This will (intentionally) not run as written so that folks
// copy-pasting have to think about how to initialize their
// Random instance.  Initialization of the Random instance is outside
// the main scope of the question, but some decent options are to have
// a field that is initialized once and then re-used as needed or to
// use ThreadLocalRandom (if using at least Java 1.7).
//
// In particular, do NOT do 'Random rand = new Random()' here or you
// will not get very good / not very random results.
Random rand;

// nextInt is normally exclusive of the top value,
// so add 1 to make it inclusive
int randomNum = rand.nextInt((max - min) + 1) + min;

return randomNum;
}
``````

See the relevant JavaDoc. In practice, the java.util.Random class is often preferable to java.lang.Math.random().

In particular, there is no need to reinvent the random integer generation wheel when there is a straightforward API within the standard library to accomplish the task.

+13 votes
answered Dec 12, 2008

Try

``````rand.nextInt((max+1) - min) + min;
``````
+108 votes
answered Dec 12, 2008

Use:

``````minimum + rn.nextInt(maxValue - minvalue + 1)
``````
+18 votes
answered Dec 12, 2008 by

I wonder if any of the random number generating methods provided by an Apache Commons Math library would fit the bill.

+11 votes
answered Dec 12, 2008 by
``````int random = minimum + Double.valueOf(Math.random()*(maximum-minimun)).intValue();
``````

Or take a look to RandomUtils from Apache Commons.

+82 votes
answered Dec 12, 2008

You can edit your second code example to:

``````Random rn = new Random();
int range = maximum - minimum + 1;
int randomNum =  rn.nextInt(range) + minimum;
``````
+1280 votes
answered Dec 12, 2008

Note that this approach is more biased and less efficient than a `nextInt` approach, https://stackoverflow.com/a/738651/360211

One standard pattern for accomplishing this is:

``````Min + (int)(Math.random() * ((Max - Min) + 1))
``````

The Java Math library function Math.random() generates a double value in the range `[0,1)`. Notice this range does not include the 1.

In order to get a specific range of values first, you need to multiply by the magnitude of the range of values you want covered.

``````Math.random() * ( Max - Min )
``````

This returns a value in the range `[0,Max-Min)`, where 'Max-Min' is not included.

For example, if you want `[5,10]`, you need to cover five integer values so you use

``````Math.random() * 5
``````

This would return a value in the range `[0,5)`, where 5 is not included.

Now you need to shift this range up to the range that you are targeting. You do this by adding the Min value.

``````Min + (Math.random() * (Max - Min))
``````

You now will get a value in the range `[Min,Max)`. Following our example, that means `[5,10)`:

``````5 + (Math.random() * (10 - 5))
``````

But, this still doesn't include `Max` and you are getting a double value. In order to get the `Max` value included, you need to add 1 to your range parameter `(Max - Min)` and then truncate the decimal part by casting to an int. This is accomplished via:

``````Min + (int)(Math.random() * ((Max - Min) + 1))
``````

And there you have it. A random integer value in the range `[Min,Max]`, or per the example `[5,10]`:

``````5 + (int)(Math.random() * ((10 - 5) + 1))
``````
+10 votes
answered Dec 13, 2008 by

When you need a lot of random numbers, I do not recommend the Random class in the API. It has just a too small period. Try the Mersenne twister instead. There is a Java implementation.

+46 votes
answered Jan 8, 2009 by

The Math.Random class in Java is 0-based. So, if you write something like

``````Random rand = new Random();
int x = rand.nextInt(10);
``````

x will be between 0-9 inclusive.

So given the following array of 25 items, the code to generate a random number between 0 (the base of the array) and `array.length` would be:

``````String[] i = new String;
Random rand = new Random();
int index = 0;

index = rand.nextInt(i.Length)
``````

Since `i.Length` will return 25, the `nextInt(i.Length)` will return a number between the range of 0-24. The other option is going with `Math.Random` which works in the same way.

``````   index = (int)Math.floor(Math.random()*i.length);
``````

For a better understanding, check out forum post Random Intervals (archive.org).

+13 votes
answered Feb 16, 2010 by

In case of rolling a dice it would be random number between 1 to 6 (not 0 to 6), so:

``````face = 1 + randomNumbers.nextInt(6);
``````