Java 17 Recipes


Download 3.2 Mb.
Pdf ko'rish
bet71/245
Sana02.06.2024
Hajmi3.2 Mb.
#1839910
1   ...   67   68   69   70   71   72   73   74   ...   245
Bog'liq
Java 17 Recipes

 Solution 2
Use the Math.random() method. This produces a double value greater than 0.0, but less 
than 1.0. The following code demonstrates the use of this method.
double rand = Math.random();
 How It Works
The java.util.Random class uses a 48-bit seed to generate a series of pseudorandom 
values. As you can see from the example in the solution to this recipe, the Random class 
can generate many different types of random number values based on the given seed. 
By default, the seed is generated based on a calculation derived from the number of 
milliseconds that the machine has been active. However, the seed can be set manually 
using the Random setSeed() method. If two Random objects have the same seed, they 
produce the same results.
It should be noted that there are cases in which the Random class might not be the 
best choice for generating random values. For instance, if you are attempting to use 
a thread-safe instance of java.util.Random, you might run into performance issues 
if you’re working with many threads. In such a case, you might consider using the 
ThreadLocalRandom class instead. Similarly, if you require the use of a cryptographically 
secure Random object, consider using SecureRandom.
Chapter 4 Numbers aNd dates


119
The java.util.Random class comes in very handy when you need to generate a 
type-specified random value. Not only is it easy to use, but it also provides a wide range 
of options for the return type. Another easy technique is to use the Math.random() 
method, which produces a double value within the range of 0.0 to 1.0, as demonstrated 
in solution 2. Both techniques provide a good means of generating random values. 
However, if you need to generate random numbers of a specific type, java.util.Random 
is the best choice.

Download 3.2 Mb.

Do'stlaringiz bilan baham:
1   ...   67   68   69   70   71   72   73   74   ...   245




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling