Explain Codes LogoExplain Codes Logo

Getting random numbers in Java

java
random-number-generation
java-random
thread-safety
Alex KataevbyAlex Kataev·Nov 12, 2024
TLDR

For generating a random integers in Java, use java.util.Random:

import java.util.Random; //Keep your friends close and your imports closer Random random = new Random(); //My life now has a purpose int num = random.nextInt(100); //Generates a number that's less than 100 but higher than the chance of me getting a date.

For double values somewhere in the realm of 0.0 and 1.0:

double dbl = Math.random(); //When life gives you lemons, make doubles.

To port an inclusive range with nextInt, adjust the north pole:

int num = random.nextInt(100) + 1; //Adding 1, because zero is too mainstream.

Sculpting a specific range with a shovel named Math.random():

int num = (int) (Math.random() * 50) + 1; //50 shades of randomness.

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:

Random random = new Random(); //If life gives you random, make numbers. int min = 5; int max = 10; int num = random.nextInt((max - min) + 1) + min; // Gives random number between 5 and 10, because why not?

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:

int num = (int) (Math.random() * (max - min + 1)) + min; // Volatile mix of Math.random() and casting, use with care.

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:

int num = ThreadLocalRandom.current().nextInt(100) + 1; // Look ma, I'm thread-safe!

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:

SecureRandom secureRandom = new SecureRandom(); int secureNum = secureRandom.nextInt();

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:

Random seededRandom = new Random(42); // Answer to life, universe and everything is a seed?

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:

Set<Integer> uniqueNums = new LinkedHashSet<>(); // The United Nations of Integers! while (uniqueNums.size() < 10) { int number = random.nextInt(100) + 1; // No door too small, no integer too big uniqueNums.add(number); // Join the club, pal! }

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:

String[] colors = {"Red", "Green", "Blue"}; // An array of colors is just a rainbow waiting to happen. int index = random.nextInt(colors.length); // Which color will it be? String randomColor = colors[index]; // The color for today is...