# between - How to generate random integers within a specific range in Java?

## repetition without (25)

You can edit your second code example to:

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

How do I generate a random `int`

value in a specific range?

I have tried the following, but those do not work:

**Attempt 1:**

```
randomNum = minimum + (int)(Math.random() * maximum);
// Bug: `randomNum` can be bigger than `maximum`.
```

**Attempt 2:**

```
Random rn = new Random();
int n = maximum - minimum + 1;
int i = rn.nextInt() % n;
randomNum = minimum + i;
// Bug: `randomNum` can be smaller than `minimum`.
```

```
int random = minimum + Double.valueOf(Math.random()*(maximum-minimun)).intValue();
```

Or take a look to RandomUtils from Apache Commons.

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);
```

```
rand.nextInt((max+1) - min) + min;
```

ThreadLocalRandom equivalent of class java.util.Random for multithreaded environment. Generating a random number is carried out locally in each of the threads. So we have a better performance by reducing the conflicts.

```
int rand = ThreadLocalRandom.current().nextInt(x,y);
```

x,y - intervals e.g. (1,10)

This methods might be convenient to use:

This method will return a random number ** between** the provided min and max value:

```
public static int getRandomNumberBetween(int min, int max) {
Random foo = new Random();
int randomNumber = foo.nextInt(max - min) + min;
if (randomNumber == min) {
// Since the random number is between the min and max values, simply add 1
return min + 1;
} else {
return randomNumber;
}
}
```

and this method will return a random number ** from** the provided min and max value (so the generated number could also be the min or max number):

```
public static int getRandomNumberFrom(int min, int max) {
Random foo = new Random();
int randomNumber = foo.nextInt((max + 1) - min) + min;
return randomNumber;
}
```

I found this example Generate random numbers :

This example generates random integers in a specific range.

```
import java.util.Random;
/** Generate random integers in a certain range. */
public final class RandomRange {
public static final void main(String... aArgs){
log("Generating random integers in the range 1..10.");
int START = 1;
int END = 10;
Random random = new Random();
for (int idx = 1; idx <= 10; ++idx){
showRandomInteger(START, END, random);
}
log("Done.");
}
private static void showRandomInteger(int aStart, int aEnd, Random aRandom){
if ( aStart > aEnd ) {
throw new IllegalArgumentException("Start cannot exceed End.");
}
//get the range, casting to long to avoid overflow problems
long range = (long)aEnd - (long)aStart + 1;
// compute a fraction of the range, 0 <= frac < range
long fraction = (long)(range * aRandom.nextDouble());
int randomNumber = (int)(fraction + aStart);
log("Generated : " + randomNumber);
}
private static void log(String aMessage){
System.out.println(aMessage);
}
}
```

An example run of this class :

```
Generating random integers in the range 1..10.
Generated : 9
Generated : 3
Generated : 3
Generated : 9
Generated : 4
Generated : 1
Generated : 3
Generated : 9
Generated : 10
Generated : 10
Done.
```

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.

If you want to try the answer with the most votes above, you can simply use this code:

```
public class Randomizer
{
public static int generate(int min,int max)
{
return min + (int)(Math.random() * ((max - min) + 1));
}
public static void main(String[] args)
{
System.out.println(Randomizer.generate(0,10));
}
}
```

It is just clean and simple.

You can achieve that concisely in Java 8:

```
Random random = new Random();
int max = 10;
int min = 5;
int totalNumber = 10;
IntStream stream = random.ints(totalNumber, min, max);
stream.forEach(System.out::println);
```

Here's a helpful class to generate random `ints`

in a range with any combination of inclusive/exclusive bounds:

```
import java.util.Random;
public class RandomRange extends Random {
public int nextIncInc(int min, int max) {
return nextInt(max - min + 1) + min;
}
public int nextExcInc(int min, int max) {
return nextInt(max - min) + 1 + min;
}
public int nextExcExc(int min, int max) {
return nextInt(max - min - 1) + 1 + min;
}
public int nextIncExc(int min, int max) {
return nextInt(max - min) + min;
}
}
```

```
rand.nextInt((max+1) - min) + min;
```

This is working fine.

Forgive me for being fastidious, but the solution suggested by the majority, i.e., `min + rng.nextInt(max - min + 1))`

, seems perilous due to the fact that:

`rng.nextInt(n)`

cannot reach`Integer.MAX_VALUE`

.`(max - min)`

may cause overflow when`min`

is negative.

A foolproof solution would return correct results for any `min <= max`

within [`Integer.MIN_VALUE`

, `Integer.MAX_VALUE`

]. Consider the following naive implementation:

```
int nextIntInRange(int min, int max, Random rng) {
if (min > max) {
throw new IllegalArgumentException("Cannot draw random int from invalid range [" + min + ", " + max + "].");
}
int diff = max - min;
if (diff >= 0 && diff != Integer.MAX_VALUE) {
return (min + rng.nextInt(diff + 1));
}
int i;
do {
i = rng.nextInt();
} while (i < min || i > max);
return i;
}
```

Although inefficient, note that the probability of success in the `while`

loop will always be 50% or higher.

Note that this approach is more biased and less efficient than a `nextInt`

approach, https://.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))
```

With java-8 they introduced the method `ints(int randomNumberOrigin, int randomNumberBound)`

in the `Random`

class.

For example if you want to generate five random integers (or a single one) in the range [0, 10], just do:

```
Random r = new Random();
int[] fiveRandomNumbers = r.ints(5, 0, 11).toArray();
int randomNumber = r.ints(1, 0, 11).findFirst().getAsInt();
```

The first parameter indicates just the size of the `IntStream`

generated (which is the overloaded method of the one that produces an unlimited `IntStream`

).

If you need to do multiple separate calls, you can create an infinite primitive iterator from the stream:

```
public final class IntRandomNumberGenerator {
private PrimitiveIterator.OfInt randomIterator;
/**
* Initialize a new random number generator that generates
* random numbers in the range [min, max]
* @param min - the min value (inclusive)
* @param max - the max value (inclusive)
*/
public IntRandomNumberGenerator(int min, int max) {
randomIterator = new Random().ints(min, max + 1).iterator();
}
/**
* Returns a random number in the range (min, max)
* @return a random number in the range (min, max)
*/
public int nextInt() {
return randomIterator.nextInt();
}
}
```

You can also do it for `double`

and `long`

values.

Hope it helps! :)

```
public static Random RANDOM = new Random(System.nanoTime());
public static final float random(final float pMin, final float pMax) {
return pMin + RANDOM.nextFloat() * (pMax - pMin);
}
```

Generate a random number for the difference of min and max by using the nextint(n) method and then add min number to the result:

```
Random rn = new Random();
int result = rn.nextInt(max - min + 1) + min;
System.out.println(result);
```

```
private static Random random = new Random();
public static int getRandomInt(int min, int max){
return random.nextInt(max - min + 1) + min;
}
```

OR

```
public static int getRandomInt(Random random, int min, int max)
{
return random.nextInt(max - min + 1) + min;
}
```

Let us take an example.

Suppose I wish to generate a number between **5-10**:

```
int max = 10;
int min = 5;
int diff = max - min;
Random rn = new Random();
int i = rn.nextInt(diff + 1);
i += min;
System.out.print("The Random Number is " + i);
```

*Let us understand this*...

Initialize max with highest value and min with the lowest value.

Now, we need to determine how many possible values can be obtained. For this example, it would be:

5, 6, 7, 8, 9, 10So, count of this would be max - min + 1.

i.e. 10 - 5 + 1 = 6

The random number will generate a number between

0-5.i.e. 0, 1, 2, 3, 4, 5

Adding the

minvalue to the random number would produce:5, 6, 7, 8, 9, 10

Hence we obtain the desired range.

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

It's better to use SecureRandom rather than just Random.

```
public static int generateRandomInteger(int min, int max) {
SecureRandom rand = new SecureRandom();
rand.setSeed(new Date().getTime());
int randomNum = rand.nextInt((max - min) + 1) + min;
return randomNum;
}
```

Use:

```
Random ran = new Random();
int x = ran.nextInt(6) + 5;
```

The integer `x`

is now the random number that has a possible outcome of `5-10`

.

Just use the Random class:

```
Random ran = new Random();
// Assumes max and min are non-negative.
int randomInt = min + ran.nextInt(max - min + 1);
```

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

For example: `RandomDataGenerator.nextInt`

or `RandomDataGenerator.nextLong`

Don't really like any of this answers regarding "simple" solution :S

I would go for a simple ;), pure java, one liner (entropy is based on random string length and the given character set):

```
public String randomString(int length, String characterSet) {
return IntStream.range(0, length).map(i -> new SecureRandom().nextInt(characterSet.length())).mapToObj(randomInt -> characterSet.substring(randomInt, randomInt + 1)).collect(Collectors.joining());
}
@Test
public void buildFiveRandomStrings() {
for (int q = 0; q < 5; q++) {
System.out.println(randomString(10, "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"));//charachterSet can basically be anything
}
}
```

or (a bit more readable old way)

```
public String randomString(int length, String characterSet) {
StringBuilder sb = new StringBuilder(); //consider using StringBuffer if needed
for (int i = 0; i < length; i++) {
int randomInt = new SecureRandom().nextInt(characterSet.length());
sb.append(characterSet.substring(randomInt, randomInt + 1));
}
return sb.toString();
}
@Test
public void buildFiveRandomStrings() {
for (int q = 0; q < 5; q++) {
System.out.println(randomString(10, "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")); //charachterSet can basically be anything
}
}
```

But on the other hand you could also go with UUID which has a pretty good entropy (https://en.wikipedia.org/wiki/Universally_unique_identifier#Collisions):

```
UUID.randomUUID().toString().replace("-", "")
```

Hope that helps.