2008-12-12 18:20:57 8 Comments

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

### Related Questions

#### Sponsored Content

#### 19 Answered Questions

#### 22 Answered Questions

### [SOLVED] Generate random number between two numbers in JavaScript

**2011-02-10 16:41:22****Mirgorod****1449886**View**1795**Score**22**Answer- Tags: javascript random

#### 31 Answered Questions

#### 69 Answered Questions

### [SOLVED] Generate random string/characters in JavaScript

**2009-08-28 21:14:41****Tom Lehman****1402469**View**1776**Score**69**Answer- Tags: javascript random

#### 44 Answered Questions

### [SOLVED] How do I convert a String to an int in Java?

**2011-04-07 18:27:54****Unknown user****5958258**View**3026**Score**44**Answer- Tags: java string int type-conversion

#### 57 Answered Questions

### [SOLVED] How to create a memory leak in Java?

**2011-06-24 16:11:52****Mat B.****637695**View**3221**Score**57**Answer- Tags: java memory memory-leaks

#### 42 Answered Questions

### [SOLVED] How do I efficiently iterate over each entry in a Java Map?

**2008-09-05 21:12:48****iMack****2475843**View**3300**Score**42**Answer- Tags: java dictionary collections iteration

#### 36 Answered Questions

### [SOLVED] Generating random whole numbers in JavaScript in a specific range?

**2009-10-06 20:05:41****zacharyliu****1279337**View**1954**Score**36**Answer- Tags: javascript random integer

#### 42 Answered Questions

### [SOLVED] How to generate a random alpha-numeric string?

**2008-09-03 02:58:43****Todd****1382440**View**1741**Score**42**Answer- Tags: java string random alphanumeric

#### 59 Answered Questions

### [SOLVED] How do I read / convert an InputStream into a String in Java?

**2008-11-21 16:47:40****Johnny Maelstrom****2112065**View**4062**Score**59**Answer- Tags: java string io stream inputstream

## 30 comments

## @Anand 2020-05-29 04:47:33

Use Apache Lang3 Commons

Min Value 100000 to Max Value 999999

## @Rahul Dhiman 2019-12-16 10:56:17

The following snippet will give a random value between 0 and 10000:

## @Toby Speight 2019-12-16 11:17:54

Thank you for this code snippet, which might provide some limited short-term help. A proper explanation would greatly improve its long-term value by showing

whythis is a good solution to the problem, and would make it more useful to future readers with other, similar questions. Please edit your answer to add some explanation, including the assumptions you've made. In particular, it's not obvious how this code accepts the lower and upper bounds of the problem statement.## @Lokesh Sharma 2020-05-04 14:48:10

int func(int max, int min){

}

## @Alexis C. 2014-11-26 18:29:07

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:

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:

You can also do it for

`double`

and`long`

values. I hope it helps! :)## @Naxos84 2018-02-26 07:13:43

I would suggest that you instantiate the randomIterator only once. See Greg Case comment on his own answer.

## @Erfan Ahmed 2018-04-10 10:39:40

if you may, can you explain what is the significance of

`streamSize`

- the first param of this method given`streamSize !=0`

. What is the difference if`streamSize`

1/2/n is given?## @andrew 2013-02-12 23:19:46

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

,`y`

- intervals e.g. (1,10)## @Simon 2017-05-28 14:30:49

I use this:

You can cast it to an Integer if you want.

## @sokras 2017-07-20 07:38:51

This function produces the same number over and over again. In my case it was: 2147483647

## @Maarten Bodewes 2018-04-23 21:26:54

Fail: you have a function that requires a double and then perform + 1? This certainly goes against the principle of least surprise. What happens if you use min = 0.1 and max = 0.2?

## @Maarten Bodewes 2018-04-23 21:36:31

@sokras the method calls

`new Random`

(check the JavaDoc): "Creates a new random number generator. This constructor sets the seed of the random number generator to a value very likely to be distinct from any other invocation of this constructor." Very likely might just involve using the current time as seed. If that time uses milliseconds then current computers are fast enough to generate the same number. But besides that 2147483647 is`Integer.MAX_VALUE`

; the output obviously depends on the input, which you haven't specified.## @Jency 2019-12-24 11:11:37

Finally found the one that actually works

## @Kaplan 2019-07-06 09:02:40

here's a function that returns exactly one integer random number in a range defined by`lowerBoundIncluded`

and`upperBoundIncluded`

, as requested byuser42155`SplittableRandom splittableRandom = new SplittableRandom();`

`randomInt.apply( …, … ); // gets the random number`

…or shorter for the one-time generation of a random number## @Abel Callejo 2013-09-01 02:53:53

It can be done by simply doing the statement:

Below is its source-code

## Randomizer.java

It is just clean and simple.

## @Maarten Bodewes 2017-06-19 21:23:47

This could have been an edit of the other example, now it is just a blatant copy for reputation. Pointing out the "answer with the most votes" is also not very direct, it can change.

## @Abel Callejo 2017-06-20 00:36:07

That is right @MaartenBodewes. When I wrote this answer, the answer with the most votes above was still written as an algorithm-like solution. Now, the solution above has changed a lot and now this answer looked like a copy-cat.

## @Leevi L 2019-10-08 08:31:53

I really don't get why such fundamental bits of code are not part of Java standard libraries. Why do I have to implement this?

## @anshul 2019-05-13 09:04:30

Following code could be used:

## @Maarten Bodewes 2019-07-01 11:28:27

There have been multiple answers that already suggested

`ThreadLocalRandom`

. If a question has been protected then please take extra care not to duplicate answers.## @AZ_ 2011-07-13 11:31:55

## @Prof Mo 2013-12-24 13:33:13

Just use the Random class:

## @Maarten Bodewes 2017-06-19 21:21:53

I don't see anything new here that hadn't been posted in countless earlier posts.

## @gifpif 2015-05-27 10:43:08

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:

## @Gihan Chathuranga 2017-08-12 14:10:39

This is the easy way to do this.

In there 5 is the starting point of random numbers. 6 is the range including number 5.

## @Sam2016 2017-10-04 14:18:05

A simple way to generate n random numbers between a and b e.g a =90, b=100, n =20

`r.ints()`

returns an`IntStream`

and has several useful methods, have look at its API.## @Maarten Bodewes 2020-05-05 19:51:55

Besides there being other answers that use streams, at least they don't create a new stream within a loop, now that really doesn't make sense.

## @Hospes 2012-06-07 10:38:41

I found this example Generate random numbers :

This example generates random integers in a specific range.

An example run of this class :

## @Luke Taylor 2012-08-12 15:01:37

This methods might be convenient to use:

This method will return a random number

the provided min and max value:betweenand this method will return a random number

the provided min and max value (so the generated number could also be the min or max number):from## @Maarten Bodewes 2017-03-01 21:26:35

`// Since the random number is between the min and max values, simply add 1`

. Why? Doesn't min count? Usually the range is [min, max) where min is included and max is excluded. Wrong answer, voted down.## @Luke Taylor 2017-03-02 09:53:53

@MaartenBodewes +1 is added because getRandomNumberBetween generates a random number exclusive of the provided endpoints.

## @Lii 2018-06-17 12:21:50

The number

`min + 1`

will be twice as likely than the other number to be the result of`getRandomNumberBetween`

!## @BMAM 2018-02-01 04:54:58

The below code generates a random number between 100,000 and 900,000. This code will generate six digit values. I'm using this code to generate a six-digit OTP.

Use

`import java.util.Random`

to use this random method.## @hexabunny 2015-03-12 22:44:28

Just a small modification of your first solution would suffice.

See more here for implementation of

`Random`

## @AxelH 2016-07-08 12:30:15

For minimum <= value < maximum, I did the same with Math :

randomNum = minimum + (int)(Math.random() * (maximum-minimum));but the casting isn't really nice to see ;)## @Maarten Bodewes 2020-05-05 19:55:11

At least 7 years late duplicate answer.

## @Matt R 2009-01-08 15:04:42

The

`Math.Random`

class in Java is 0-based. So, if you write something like this:`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: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.For a better understanding, check out forum post

Random Intervals (archive.org).## @Tapper7 2016-10-30 05:44:57

+1 for wayBackMachine archive screenshot link & your answer is still useful reference to get "random" ints w/in a range.

## @AjahnCharles 2017-08-02 13:53:53

It baffles me why you instantiate index to 0.

## @Matt R 2017-08-02 14:38:52

@CodeConfident The

`index`

variable will not affect the result of the random number. You can choose to initialize it any way you would like without having to worry about changing the outcome. Hope this helps.## @AjahnCharles 2017-08-02 14:41:09

Exactly... it's completely unused. I would initialise it directly to the rand:

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

## @Mark Storer 2019-09-17 18:24:35

Or not at all.

`int index; \n index = rand...`

if one is fond of declarations and assignments on different lines. Some coding standards are more stringent (and without apparent purpose) than others.## @jackson 2009-09-04 04:23:27

Use:

The integer

`x`

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

.## @Mulalo Madida 2017-06-20 12:39:17

You can achieve that concisely in Java 8:

## @Sunil Chawla 2014-08-03 03:07:54

Let us take an example.

Suppose I wish to generate a number between

5-10:Let us understand this...## @TJ_Fischer 2008-12-12 18:35:49

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

`nextInt`

approach, https://stackoverflow.com/a/738651/360211One standard pattern for accomplishing this is:

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.

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

You now will get a value in the range

`[Min,Max)`

. Following our example, that means`[5,10)`

: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:And there you have it. A random integer value in the range

`[Min,Max]`

, or per the example`[5,10]`

:## @Lilian A. Moraru 2012-02-23 23:26:34

The Sun documentation explicitly says that you should better use Random() if you need an int instead of Math.random() which produces a double.

## @weston 2016-12-29 13:35:53

This is actually biased compared to nextInt methods stackoverflow.com/a/738651/360211

## @Cephalopod 2019-08-29 09:48:18

"Biased" in this case means that after 2^53 executions, some numbers will have had one extra occourance, on average.

## @Alekya 2018-08-22 06:46:32

## @user2427 2008-12-12 18:28:35

Or take a look to RandomUtils from Apache Commons.

## @zakmck 2015-01-30 09:27:17

That's useful, but beware a small flaw: method signatures are like: nextDouble(double startInclusive, double endInclusive), but if you look inside the methods, endInclusive should actually be endExclusive.

## @Holger 2016-06-03 09:47:15

`Double.valueOf(Math.random()*(maximum-minimun)).intValue()`

is quite an obfuscated (and inefficient) way to say`(int)(Math.random()*(maximum-minimun))`

…## @Hrishikesh Mishra 2016-12-26 05:14:23

Spelling mismatch for minimum return minimum + Double.valueOf(Math.random() * (maximum - minimum)).intValue();

## @Anjali Pavithra 2019-01-01 09:39:04

Below is a sample class which shows how to generate random integers within a specific range. Assign any value you want as the maximum value to the variable 'max' and assign any value you want as the minimum value to the variable 'min'.

## @Prakhar Nigam 2018-11-17 07:46:35

Use java.util for Random for general use.

You can define your minimum and maximum range to get those results.

## @monster 2018-08-14 12:25:54

Making the following change in

Attempt 1should do the work -Check this for working code.

## @Siddhartha Thota 2018-02-25 20:26:34

Say you want range between 0-9, 0 is minimum and 9 is maximum. The below function will print anything between 0 and 9. It's the same for all ranges.

## @user10253771 2019-01-23 01:03:57

This doesn't look right. In "int n = (max + 1 - min) + min; return (int) (Math.random() * n);" , n = max + 1, and you are just creating an int in [0, max] instead of [min, max]. It should be "int n = max + 1 - min; return (int) (Math.random() * n) + min;"

## @namezhouyu 2017-10-09 08:48:28

## @Peter Mortensen 2019-01-05 10:21:20

An explanation would be in order.