Getting random numbers in Java
For generating a random integers in Java, use java.util.Random
:
For double values somewhere in the realm of 0.0 and 1.0:
To port an inclusive range with nextInt
, adjust the north pole:
Sculpting a specific range with a shovel named Math.random()
:
Dissecting random methods
Roving in ranges with java.util.Random
Random
allows you to control the tides of your random integers. To specify a range different from the generic 0 (inclusive) to n (exclusive), you can adjust the weather vane:
This incantation guarantees a result safely ensconced between min
(inclusive) and max
(inclusive).
Using random responsibly with Math.random()
Math.random()
is splendid when you don't need to fuss over a seed and just desire a double. But what if you yearn for an integral in a specific range? Well, shuffle the deck like so:
You are granted a random integer value from min
to max
, inclusive.
Probability parade in random
Both Random.nextInt()
and Math.random()
bless you with a uniform distribution of numbers. However, if you fancy a different distribution, like the bell curve of normal or the slide of exponential, you might need additional tools or algorithms, or maybe just a fortune cookie.
Playing in traffic: thread safety and random generation
Threads can be as unpredictable as a baby on sugar. Random
doesn't jive well with multiple threads. If your code loves to run like a dozen kids in a park, choose ThreadLocalRandom
:
Keeping secrets with cryptographic security
If your app is a secret agent, normal Random
or Math.random()
won't cut it. Instead, assign SecureRandom
to your secret mission:
Pro tips for random number generation
Dabbling with seeds for reproducibility
Seeds are the secret herbs and spices in your random recipe. They help you whip up a predictable sequence of numbers, perfect for taste testing or re-enacting glorious battle simulations:
Generating a unique array of random numbers
If you crave random numbers without an echo, a Set
can dance with the Random
class like nobody's business:
Avoid the bias trap in random choice
Don't be biased when performing a random selection from a collection. To ensure fair-play, use nextInt
with the collection's size:
Was this article helpful?