0 ratings0% found this document useful (0 votes) 64 views9 pagesRandam in Java
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, 
claim it here.
Available Formats
Download as PDF or read online on Scribd
512212021 Random Number Generation in Java - DZone Java
DZone. 4 & Wuserstoginnimy — Q (/search)
REFCARDZ (/refcardz) RESEARCH (/research) WEBINARS (/webinars) ZONES v
DZone (/) > Java Zone (|java-idk-development-tutorials-tools-news) > Random Number Generation in Java
Random Number Generation in Java
(Jusers/2520536/john-1.html) by John Thompson (/users/2520536/john-1.html) &MVB -
Dec. 26, 17 « Java Zone (/java-jdk-development-tutorials-tools-news) * Tutorial
© Like (31) g@Comment (5) YY Save W Tweet
[Report] The Total Cost of Ownership for Cloud Databases
What are all the costs that you need to account for when evaluating
commitment to a cloud database? Learn how to evaluate the total ¢
database in this free guide. Download for Free »
 
® Cockroach Labs
While developing applications, we often need to generate random numbers. Java
provides support for generating random numbers primarily through the java.lang.Math
(https: //docs.oracle.com /javase/8 /docs/api/java/lang/Math.html) and
java.util, Random (https://docs.oracle.com /javase/8 /docs/api/java/util/Random.html)
classes,
In this post, I will discuss different ways to generate random numbers based on
different types of requirements.
Random Numbers Using the Math Class
Java provides the Math class in the java.util package to generate random numbers.
The Math class contains the static Math.random() method to generate random numbers
of the double type.
The random() method returns a double value with a positive sign, greater than or equal
to 0.0 and less than 1.0. When you call Math.random(), under the hood, a
java.util.Random pseudorandom-number generator object is created and used.
hitps dzone. convatilesirandom-number-generatonin-java 19512272021 Ronom Number Generation ava - DZone Jove
@RZal MGs random method with or widoutuperssinig bavamet@s. (/arch)
reveondds paransteite tal PEL BEG" REBEARE RUA ETS SURES the given
parameters,
The code to use the Math.random() method:
1 public static double getRandomNunber(){
2 double x = Math.random() 5
3 return x;
ay
The getRandomNumber() method uses the Math.random() method to return a positive
double value that is greater than or equal to 0,0 and less than 1.0.
The output of running the code is:
1 Double between 0.0 and 1.0: SimpleRandonNumber = 0.21753313144345698
Random Numbers Within a Given Range
For generating random numbers between a given a range, you need to specify the
range. A standard expression for accomplishing this is:
1 (Math.random() * ((max + min) + 1)) + min
Letus break this expression into steps:
1. First, multiply the magnitude of the range of values you want to cover by the result
that Math.random() produces.
Math.random() * ( max - min ) returnsa value in the range [0, max - min]
where max is excluded. For example, if you want [5,10], you need to cover
integer values so you can use Math.random()*5. This would return a value in the
range [0,5], where 5 is not included.
2. Next, shift this range up to the range that you are targeting, You do this by adding
hitps dzone. convatilesirandom-number-generaton-in-java 29512212021 Random Number Generation in Java - DZone Java
pane:
one. & (isersioginnimy Q (/search)
(Math.random() * ( max - min )) + min
REFCARDZ (/refcardz) RESEARCH (/research) WEBINARS (webinars) ZONES »
But this still does not include the maximum value.
  
* To get the max value included, you need to add 1 to your range parameter
(max - min). This will return a random double within the specified range.
double x = (Math.random()*((max-min)+1))-+min;
There are different ways of implementing the above expression, Let us look ata couple
of them.
 
Random Double Within a Given Range
By default, the Math.random() method returns a random number of the type double
whenever it is called, The code to generate a random double value between a specified
range is:
1 public static double getRandonboubleBetweenRange(double min, double max){
2 double x = (Math.random()*((max-min)+1))+min;
3 return x;
4)
You can call the preceding method from the main method by passing the arguments like
this.
1 System.out.printIn("Double between 5.@ and 10.2: RandomDoubleNunber = "+getRandonDoubleBetwe,
The outputs this,
1 System.out.println("Double between 5.0 and 10.00:
 
RandonDoubleNunber = +getRandonDoubleBetwe:
Random Integer Within a Given Range
The code to generate a random integer value between a specified range is this.
1 public static double getRandomIntegerBetweenRange(double min, double max){
hitps dzone. convatilesirandom-number-generaton-in-java 39512212021
    
& Wserstoginnimy)  Q (/search)
REFCARDZ (/refcardz) RESEARCH (/research) WEBINARS (/webinars) ZONES v
The preceding getRandomIntegerBetweenRange() method produces a random integer
between the given range. As Math.random() method generates random numbers of
double type, you need to truncate the decimal part and cast it to int in order to get the
integer random number. You can call this method from the main method by passing the
arguments as follows:
1 System.out.printIn("Integer between 2 and 6: RandomIntegerNumber = “+getRandonIntegerBetweenk
The output is this.
1 Integer between 2 and 6: RandonIntegerNunber = 5
Note: You can pass a range of negative values to generate a random negative number
within the range.
Random Number Generation Using the Random
Class
You can use the java.util.Random class to generate random numbers of different types,
such as int, float, double, long, and boolean.
To generate random numbers, first, create an instance of the Random class and then call
one of the random value generator methods, such as nextInt(), nextDouble(), or
nextLong().
The nextint() method of Random accepts a bound integer and returns a random integer
from 0 (inclusive) to the specified bound (exclusive).
The code to use the nextInt() method is this.
1 public static int generateRandontnt(int upperRange){
2 Random random = new Random();
3 return random.nextInt (upperRange) ;
hitps dzone. convaticlesirandom-number-generaton-in-java 49512212021 Random Number Generation in Java - DZone Java
DZone. 0 & (isersioginimy _Q (/search)
REFCARDZ (/refcardz) RESEARCH (/research) WEBINARS (/webinars) ZONES ~
The code to use the nextInt() method to generate an integer within a range is:
 
1 public static int generateRandontntIntRange(int min, int max) {
2 Random r = new Random();
3 return renextInt((ax - min) + 1) + min;
ay
The nextFloat() and nextDouble() methods allow generating float and double values
between 0.0 and 1.0.
The code to use both the methods is:
 
1 public static double generateRandonbouble(){
2 Random random = new Random();
3 return randon.nextDouble}
4)
5
6 public static float generateRandonFloat(){
7 Random randon = new Random);
8 return random.nextFloat();
9}
Random Number Generation Features in Java 8
Java 8 (https://dzone.com/articles/java-8-concepts-fp-lambda-expressions-and-
streams) introduced a new method, ints(), in the java.util. Random class. The ints()
method returns an unlimited stream of pseudorandom int values. You can limit the
random numbers between a specified range by providing the minimum and the
maximum values.
The code to use the Random ints() method to generate random integer values within a
specified range is this.
1 public static int getRandomNumberInts(int min, int max){
2 Random random = new Random();
3 return random. ints (min, (maxe1)).findFirst().getastnt();
4)
hitps dzone. convatilesirandom-number-generaton-in-java 59512212021 Random Number Generation in Java - DZone Java
@ @DZone. o & (isersitoginimy Q (/search)
REPRARBZ ARSE URRRERREN LEO SORBATE AWSEES! EKA Integers between
the mir (inclusive} and max (exclusivej As inisG-uretiud produces air iniSueany die
code calls the findFirst() method that returns an Optionalint object that describes the
first element of this stream. The code then calls the getAsInt()method to return the int
   
value in Optionallnt.
The code to use the Random .ints() method to generate a stream of specified random
integer values is:
public static void getStreamOfRandomInts(int num) {
1
2 Random random = new Random();
3 random. ints (num). sorted(). forEach(System.ou
4
 
intl) 5
The code to call the preceding method is:
System.out.printn("Random int stream: RandomIntStreanofSize = ");
2 RandonDeno. getStreanofRandomints(5);
The output of the preceding code is:
1 Random int stream: RandonIntStreamofSize =
2. -1861317227
3 -1205557317
4 453883217
5 762357682
6 1725970934
The code to use the Random.ints() method to generate a stream of a specified number
of random integer values between a range is:
1 public static void getStreanOfRandomintswithRange(int num, int min, int max) {
2 Random randon = new Random();
3 randon.ints(num,min, max).sorted().for€ach(System.out: :println) ;
ay
hitps dzone. convatilesirandom-number-generaton-in-java cr512212021 Random Number Generation in Java - DZone Java
ARCO NR idreceding method is: & Wserstoginnimy)  Q (/search)
REF CAR eln Oe Foe RaNGoR WAC SEPCaN of MECN ARD SMe Linge NSoninestreanoFSizernRang.
2. RandonDeno..getStreanOFRandonIntshithRange(5, 0,10);
The output of the preceding code is:
1 Random int stream of specified size in range: RandomIntStreanofSizeInRange =
22
3
4
5
6
In addition to ints(), some other frequently used methods that Java 8 introduced to the
Random class — which can return a sequential stream of random numbers — are:
+ LongStream longs()
* DoubleStream doubles()
Summary
The java.util. Random class implements what is generally called a linear congruential
generator (https://en.wikipedia.org/wiki/Linear_congruential_generator) (LCG). Itis
designed to be fast but does not meet requirements for real-time use, such as use in
unique session ID generation on a web server, scientific experiments, cryptography, or
lotteries and sweepstakes where a monetary stake is involved. For such scenarios, there
are other alternatives, which I will cover in a later post.
For the impatient readers, you can have a look at the SecureRandom
(https: //docs.oracle.com/javase/8 /docs /api/java/security /SecureRandom html) class
and Xorshift random number generators
(https: //wwwjavamex.com/tutorials/random_numbers/xorshift shtml#.Wg7SaEqWwbl
v).
Also, an interesting resource is random.org (https://random.org/), a true random.
number service that generates randomness via atmospheric noise.
hitp.tdzone.convartclesirandom-number-generation-injava 78512212021 Random Number Generation in Java - DZone Java
DZone. 0 & (isersioginimy  Q (/search)
 
REFCARDZ (/refcardz) RESEARCH (/research) WEBINARS (/webinars) ZONES v
Topics: JAVA, RANDOM NUMBERS, JAVALANG.MATH, JAVA.UTIL.RANDOM, TUTORIAL
Published at DZone with permission of John Thompson, DZone MVB. See the original article here,
(https://springframework.guru/random-number-generation-in-java/)
Opinions expressed by DZone contributors are their own.
Popular on DZone
+ High-Performance Batch Processing Using Apache Spark and Spring Batch
(larticles/using-apache-spark-and-spring-batch-for-processing ?fromrel=true)
 
+ Checklists: System is Hacked (Part 1) Confirming a Compromise (/articles/checklists-
system-is-compromised-or-hacked-part-1 ?fromrel=true)
+ Step-by-Step Tutorial: From Data Preprocessing to Using Graph Database
(larticles/step-by-step-tutorial-from-data-preprocessing-to-u?fromrel=true)
+ Git Reset HEAD (Jarticles/git-reset-head?fromrel=true)
Java Partner Resources
ABOUT US
About DZone (Ipagesfabout)
Send feedback (mailte:support@dzone.com)
Caroers (https:lidevada.comlcareersi)
Sitemap (Isitemap)
 
ADVERTISE
Developer Marketing Blog (https:l/devada.com/blogideveloper-marketing)
» DZone (Ipages/advertise)
‘1 (919) 238-7100 (tel:+19192387100)
 
Advertise w
CONTRIBUTE ON DZONE
Article Submission Guidelines (larticlesidzones-article-submi
VB Program (Ipagesimvb)
 
hitps dzone. convatilesirandom-number-generaton-in-java 89512212021 Random Number Generation in Java - DZone Java
Upagesicontribute
GDLOASwiter-zor & Wuserstoginnimy —Q_(/search)
RERGARDZ (/refcardz) RESEARCH (/research) WEBINARS (/webinars) ZONES v
(Ipagesiprivacy)
CONTACT US
600 Park Offices Drive
Suite 150
Research Triangle Park, NC 27709
{mailto:support@dzone.com)
{tel:+19196780300)
Let's befriends: 3 yw f in
(Upadhsifteltspitt percidaheHiaitinteitctin)rndZoneipahy/dzone/)
DZone.com is powered BY Fn. wertiuy jogo (MtPslisevada.com/answerhub))
hitps dzone. convatilesirandom-number-generaton-in-java
sig
You might also like
Saño, Salvio, Uy, Villamin, Viray, Velasquez, Villablanca
Saño, Salvio, Uy, Villamin, Viray, Velasquez, Villablanca
6 pages