Week 96 — How can random numbers be generated in a Java application?

Question of the Week #96
How can random numbers be generated in a Java application?
7 Replies
0x150
0x1503mo ago
Java provides the Random utility class for generating pseudo-random numbers. If a Random object is created without any parameters, it picks a seed automatically. Alternatively, the seed can be passed in a constructor argument. Once a Random object is obtained, one can use the nextXYZ() methods to generate random numbers from it.
Random rand = new Random();//creates a Random object and let the JVM select a seed
System.out.println(rand.nextInt());//generates a random int
System.out.println(rand.nextInt(1337));//generates a random int between 0 (inclusive) and 1337 (exclusive)
System.out.println(rand.nextDouble());//generates a random double
System.out.println(rand.nextGaussian());//generates a random double that follows a standard normal distribution
Random rand = new Random();//creates a Random object and let the JVM select a seed
System.out.println(rand.nextInt());//generates a random int
System.out.println(rand.nextInt(1337));//generates a random int between 0 (inclusive) and 1337 (exclusive)
System.out.println(rand.nextDouble());//generates a random double
System.out.println(rand.nextGaussian());//generates a random double that follows a standard normal distribution
If two random objects are created with the same seed, they are yielding the same values:
Random rand = new Random(13);
System.out.println(rand.nextInt());//-1160486312
System.out.println(rand.nextInt(37));//28
System.out.println(rand.nextDouble());//0.44461356134079055
System.out.println(rand.nextGaussian());//-0.037654366027471325
Random rand = new Random(13);
System.out.println(rand.nextInt());//-1160486312
System.out.println(rand.nextInt(37));//28
System.out.println(rand.nextDouble());//0.44461356134079055
System.out.println(rand.nextGaussian());//-0.037654366027471325
Other than using the Random constructors, it is possible to obtain a Random object for the current thread using ThreadLocalRandom:
System.out.println(ThreadLocalRandom.current().nextInt());
System.out.println(ThreadLocalRandom.current().nextInt());
It is not possible to set the seed of a ThreadLocalRandom but it can result in better performance than using Random (especially in multithreaded scenarios). As Random does not provide cryptographic random numbers, it shouldn't be used for security-sensitive purposes like generating cryptographic keys. In these cases, the SecureRandom class can be used instead:
Random rand = new SecureRandom();
System.out.println(rand.nextInt());
Random rand = new SecureRandom();
System.out.println(rand.nextInt());
📖 Sample answer from dan1st
0x150
0x1503mo ago
if I want a simple random number I could use:
public int randomNumber() {
return Math.random() * 100;
}
public int randomNumber() {
return Math.random() * 100;
}
that generates a random double number between 0.0 and 1.0, on that method I've truncated the number to int and multiplied for 100, so a 0.64 turns out to be 64... and doesn't need to instantiate any new object in memory if I want a more complex, with seeds (that can be checked) I could do:
public int randomNumber(long seed) {
return new Random(seed).nextInt(100);
}
public int randomNumber(long seed) {
return new Random(seed).nextInt(100);
}
that generates a random int number with a fixed seed, so it will always be the same for that seed.. but it needs to instantiate a new object when calling, so it's recommended to create an instance outside and use it to generate new numbers
Submission from viniciuspdionizio
0x150
0x1503mo ago
To generate Random numbers in java we can simply use Randon class Random random = new Random(); int number = random.nextInt(100); System.out.print("Random Integers from 0 to 9"+ number); // this will generate random numbers between 0 and 99 // This can vary based on Data Type Such As Double and float etc.
Submission from mochpxt_67697
0x150
0x1503mo ago
we will use java.util.Random then create an object of random and then generate it like import java.util.Random; public static void main(String args[]) { // create instance of Random class Random random = new Random();
// Generate random integers in range 0 to 999 int int1 = random.nextInt(1000); int int2 = random.nextInt(1000); } }
Submission from karo_06145
0x150
0x1503mo ago
import java.util.*; public class RandomNumber { Public static void main(String[] args){ float random = Math.random() * 10; System.out.println(random); } }
Submission from mr.cool4879
0x150
0x1503mo ago
Most things needed for RNG are located in the java.util.Random class. With it one can generate different kinds of random primitives. Let's take the most useful method - Random#getInt(). It lets you generate an int from Integer.MIN_VALUE to Integer.MAX_VALUE. It's not really that useful as it is, but there's also the Random#getInt(bound) method. By using the latter method you can generate int from 0 (inclusive) to bound (exclusive). Here's an example code:
java.util.Random rand = new java.util.Random();
for(int i=0; i<5; i++) {
int number = rand.nextInt(10);
System.out.println(String.format("Number #%s is %s", i, number));
}
java.util.Random rand = new java.util.Random();
for(int i=0; i<5; i++) {
int number = rand.nextInt(10);
System.out.println(String.format("Number #%s is %s", i, number));
}
The above code will print 5 random numbers, from 0 to 9. Now, what if you wanted to generate numbers from x to x? There's also a method for that! You can use Random#nextInt(origin, bound). This method is very similar to Random#nextInt(bound), but instead of the lower bound being 0, it's the inclusive originparameter. So
new Random().nextInt(10, 21);
new Random().nextInt(10, 21);
will generate a random number from 10 to 20. With Random you can also generate other primitives, including doubles/floats, longs and even booleans nad bytes! They can be generated with nextDouble, nextFloat, nextLong, nextBoolean and nextBytes method respectively. Random can also be initialized using a seed. Seed determines what sqeuence of random numbers will get generated using this Random, hence two Randoms with the same seed will always generate the same values.
int seed = 1234;
Random rand1 = new Random(seed); // Initialize with a seed
Random rand2 = new Random(seed);
System.out.println(rand1.nextInt() == rand2.nextInt()); // Always true
int seed = 1234;
Random rand1 = new Random(seed); // Initialize with a seed
Random rand2 = new Random(seed);
System.out.println(rand1.nextInt() == rand2.nextInt()); // Always true
Even though this question is just about random numbers, it's worth noting that the java.util.Random class should not be used for cryptography! For cryptographic purposes one should use the java.security.SecureRandom class. Java also ha
0x150
0x1503mo ago
s the Math.random() method. It's similar to random methods you can find in functional programming languages. This method is essentially the same as Random#nextDouble(). It generates a double between 0.0 and 1.0. It's great when you need a random value without having a Random instance. Example usage:
if(Math.random() < 0.5) {
System.out.println("There was a 50% chance of this text appearing");
} else {
System.out.println("There also was a 50% chance of the other text appearing");
}
if(Math.random() < 0.5) {
System.out.println("There was a 50% chance of this text appearing");
} else {
System.out.println("There also was a 50% chance of the other text appearing");
}
⭐ Submission from java.net.defective

Did you find this page helpful?