Question 3: "How do I generate random integers within a specific range in Java?"

Java - Top 10 Most Viewed Questions on Stack Overflow Question 3: "How do I generate random integers within a specific range in Java?"
15 minutes
Share the link to this page
Copied
  Completed
You need to have access to the item to view this lesson.
One-time Fee
$69.99
List Price:  $99.99
You save:  $30
€64.99
List Price:  €92.85
You save:  €27.85
£55.77
List Price:  £79.68
You save:  £23.90
CA$95.68
List Price:  CA$136.70
You save:  CA$41.01
A$105.96
List Price:  A$151.38
You save:  A$45.42
S$94.48
List Price:  S$134.98
You save:  S$40.50
HK$546.78
List Price:  HK$781.15
You save:  HK$234.36
CHF 63.33
List Price:  CHF 90.48
You save:  CHF 27.14
NOK kr761.11
List Price:  NOK kr1,087.35
You save:  NOK kr326.23
DKK kr485.02
List Price:  DKK kr692.92
You save:  DKK kr207.89
NZ$116.44
List Price:  NZ$166.35
You save:  NZ$49.91
د.إ257.06
List Price:  د.إ367.25
You save:  د.إ110.18
৳7,660.01
List Price:  ৳10,943.35
You save:  ৳3,283.33
₹5,835.78
List Price:  ₹8,337.18
You save:  ₹2,501.40
RM331.75
List Price:  RM473.95
You save:  RM142.20
₦86,437.65
List Price:  ₦123,487.65
You save:  ₦37,050
₨19,492.21
List Price:  ₨27,847.21
You save:  ₨8,355
฿2,572.74
List Price:  ฿3,675.50
You save:  ฿1,102.76
₺2,264.43
List Price:  ₺3,235.04
You save:  ₺970.61
B$355.02
List Price:  B$507.19
You save:  B$152.17
R1,295.44
List Price:  R1,850.71
You save:  R555.27
Лв127.05
List Price:  Лв181.51
You save:  Лв54.46
₩94,909.58
List Price:  ₩135,590.93
You save:  ₩40,681.35
₪260.15
List Price:  ₪371.66
You save:  ₪111.51
₱3,993.87
List Price:  ₱5,705.78
You save:  ₱1,711.90
¥10,713.01
List Price:  ¥15,304.96
You save:  ¥4,591.95
MX$1,187.73
List Price:  MX$1,696.83
You save:  MX$509.10
QR254.83
List Price:  QR364.06
You save:  QR109.23
P950.82
List Price:  P1,358.38
You save:  P407.55
KSh9,247.76
List Price:  KSh13,211.65
You save:  KSh3,963.89
E£3,352.12
List Price:  E£4,788.95
You save:  E£1,436.83
ብር4,006.43
List Price:  ብር5,723.72
You save:  ብር1,717.28
Kz58,511.64
List Price:  Kz83,591.64
You save:  Kz25,080
CLP$65,950.47
List Price:  CLP$94,219
You save:  CLP$28,268.52
CN¥506.53
List Price:  CN¥723.65
You save:  CN¥217.11
RD$4,055.76
List Price:  RD$5,794.19
You save:  RD$1,738.43
DA9,420.16
List Price:  DA13,457.95
You save:  DA4,037.79
FJ$157.70
List Price:  FJ$225.30
You save:  FJ$67.59
Q542.52
List Price:  Q775.06
You save:  Q232.54
GY$14,601.52
List Price:  GY$20,860.22
You save:  GY$6,258.69
ISK kr9,773.40
List Price:  ISK kr13,962.60
You save:  ISK kr4,189.20
DH703.98
List Price:  DH1,005.73
You save:  DH301.75
L1,236.34
List Price:  L1,766.28
You save:  L529.93
ден3,998.26
List Price:  ден5,712.05
You save:  ден1,713.78
MOP$561.77
List Price:  MOP$802.57
You save:  MOP$240.79
N$1,291.99
List Price:  N$1,845.78
You save:  N$553.78
C$2,569.36
List Price:  C$3,670.67
You save:  C$1,101.31
रु9,319.09
List Price:  रु13,313.56
You save:  रु3,994.46
S/260.54
List Price:  S/372.22
You save:  S/111.67
K269.79
List Price:  K385.44
You save:  K115.64
SAR262.50
List Price:  SAR375.01
You save:  SAR112.51
ZK1,882.68
List Price:  ZK2,689.66
You save:  ZK806.98
L323.40
List Price:  L462.03
You save:  L138.62
Kč1,628.77
List Price:  Kč2,326.92
You save:  Kč698.14
Ft25,334.28
List Price:  Ft36,193.38
You save:  Ft10,859.10
SEK kr755.02
List Price:  SEK kr1,078.64
You save:  SEK kr323.62
ARS$61,468.17
List Price:  ARS$87,815.44
You save:  ARS$26,347.26
Bs483.33
List Price:  Bs690.51
You save:  Bs207.17
COP$271,845.87
List Price:  COP$388,367.89
You save:  COP$116,522.02
₡35,672.25
List Price:  ₡50,962.55
You save:  ₡15,290.29
L1,724.16
List Price:  L2,463.20
You save:  L739.03
₲522,510.75
List Price:  ₲746,475.93
You save:  ₲223,965.17
$U2,674.97
List Price:  $U3,821.56
You save:  $U1,146.58
zł281.37
List Price:  zł401.98
You save:  zł120.60
Already have an account? Log In

Transcript

The third most viewed question on Stack Overflow with over 3.8 million views over the years is how do I generate random interest within a specific range in Java? So, yeah, it's a usual use case to, to generate random numbers. Yeah, wherever you, you need random things. You can manage them by random interests or random numbers. So it's a use case. That is, very often I would say, central class for random things is Java util.

Random class. And this class has different different methods to generate random things. So in general, it's random numbers. And you have the opportunity to create different data types of numbers. So For example, you can create a random int, random doubles, random nouns and so on. But, as the name random suggests, it isn't random numbers or something like this, but just random.

So you have the opportunity to generate, for example, random Boolean, as you can see here, Boolean. And there is a method called next Boolean, and it creates random Boolean. So if you need random Williams, this class is also your friend, not only for numbers. And yeah, let's have a look at the next int method. And it returns only an int. And this method creates an int with in the whole range of the data type int.

So it's, yeah, it's very big. And you can produce in random random The integer a random int in the, in the whole range of this data type with this method. And if you need an integer within a specific range and defined range, that's the question you should use the next int worth int as parameter, this one. So I call it the parameter bound in our case, and if you do so, you get an integer Ah, returned random integer returned by with the, with this in this range. Zero is inclusive, and boundless exclusive. Yeah.

So in this range, you get one and be aware of the parameter bound. If you pass bound with zero in this example, in the In this method, you get a range zero inclusive and zero excessive so there isn't a range word with this with this a numbers. So it would throw an illegal argument exception if you if you pass a zero or less than zero in this method, so be aware of it and always pass one or greater or bigger than one. Yeah, into it, and then you get such an random integer. If you need a random floating point number, for example, double, then you should use the next double method on its own. If you use it on its own next, just next cover, you get an random double within the range of zero to one.

So does this what you get if you call next double and if you Need A w within a specific range. For example, from zero to 50 you have to multiply this random generated w with the bound as bound should be integer in this case. And, yeah, for example, bound should be 50. And the resizing number floating point number, reciting double in this case would be in the range of zero and 50 both inclusive. So let's take a look at an example. We create an instance of the random class with using the default constructor constructor.

And after that, we call it the while we use the random instance and called the next end, were forgiven. As variable in it, and we, we increment i, every every loop over the for loop and by 10. And yeah, we then output first the range and after it the computed random entered into Java, I say integer, but I mean, the primitive int data type. So that's for sure only an example we are computing random numbers. So yeah, they are random if you will try it on your own. You have different numbers for sure.

But as you can see, the the range is set. So in this case, we have the maximum 20 And so on. So, that would be that would be the thing with, with interest. And if you want to use random doubles, you can, as I said, you should use random dot next double and multiply it with another int, for example, if you need a double within a bigger range than zero, and one, and in our case we are using as that does the same range as above. So, and yeah, multiplied with next double, and as you can see, it works very well and it do what we want. So we create an random double, in this case within a specific range.

You might see or you might know, the computation of random integer random numbers. Sorry. very usual, with the math class and the random method. Yeah, you can see it in many, many times and other codes. And if you take a look what what happens there at the random method within the math class, it's investing into internally it is using just a random class. And if you call the random method, the math class invokes the next double method on the intern random instance.

So the technique of creating random doubles within the math class is exactly the same as we saw before. With the with the limitation that random is only from zero to One for sure. Like the method next hour. Yeah, but it's the same one. So if you see this one you can remember, okay, it's the random class. And random class is the most flexible one to do.

So two random things. If you are writing an application that uses several threads, and more than one thread needs a random number, you should think about if you would use the same random instance, random in a random class itself is thread safe. So it sends also in the in the Java, Java API, but you could face performance degradation if you use the same instance within different or with different threats. So let's take a look at the API. There. It is instances of random are thread safe okay.

So you could use it if you want. But however, to compute concurrent use of the same random instance across threads may encounter contention and consequent poor performance. Consider instead using thread local random and multi threaded designs. So yeah, it may be the leads to a poor performance or poor performance and consider instead of using the thread local random class, so let's take a look at an example. And for this, we go to the to eclipse and I just open to question three comma and the class thread local random. That is suggested for this is an extension of the random class.

So itself, so random this one. And if you are in a multi threaded application, you should or could use the thread local random. And as you can see, it's an instance of random. So the same methods are provided and so on. But yeah, with a better performance. So let's try it out the performance difference.

So what do we do here we have a fixed pool or thread pool for fixed size with 100 threads. And for this 100 threads, we have 1 million times to task to create an integer random integer. So we call we have above here an instance of random for random class and with this random class on this random class instance we are calling the next int method and this one million times, so, it creates 1 million random int with 100 threads concurrently and this we we we take the timestamps before So, here, then we invoke all all the coilovers all 1 million tasks at once and we are waiting the method invoke all weights to the computation of 1 million random integers or random numbers is done and after that, we will take a look about on the difference between screen this time stamp and now and yeah the difference in milli Millis.

So, after that we do the same with 100 threats, we empty the carnivals ArrayList and then again 1 million tasks, but we are using a thread local random class. And you as you can see, you should use it or you have to use it with the current method. And you can call the next int method like above, but not as here with the same random instance. But the thread local random. And yeah, as we did before, we are taking the timestamp here, we compute all invoke all and after that, we can payoff the difference between the both? And let's have a look.

All right, so you can see the difference in this case isn't too big and that thick. It's Let's have another look. Okay, here it is the half of the time. So it's very, it's, it's an impressive difference. Here again, okay. But as I said, or as I showed you in the in the API that it may encounter, poor performance.

It don't have to. It all only May. So it possible that the second approach is sometimes it is slower than the first one. Ah, now, all right. So the first one using while sharing the random instance, is in this case faster than the using thread local random. But as you can see, mostly after the runs to perform performance of the first approach is is slower than on the second one.

So, it's the recommendation. You don't have to do it but you don't have to do it because random is thread safe, but you may think about it to use it. In multi threaded applications, alright, that's the question why that's the explanation of the question how you generate random numbers random integers, random doubles within Java.

Sign Up

Share

Share with friends, get 20% off
Invite your friends to LearnDesk learning marketplace. For each purchase they make, you get 20% off (upto $10) on your next purchase.