How to Set Random Seed in Java
Aryan Tyagi
Feb 02, 2024
-
Use the
setSeed()
Function to Set Seed for Random Numbers in Java -
Use the
Random
Constructor to Set Seed for Random Number in Java
A seed is a number or a vector assigned to a pseudo-random generator to produce the required sequence of random values. If we pass the same seed, it will generate the same sequence. We usually assign the seed as system time. This way, it will produce a different sequence every time.
We will discuss how to generate random numbers using seed in Java in this article.
Use the setSeed()
Function to Set Seed for Random Numbers in Java
The setSeed()
function of the Random class uses a single long seed to set the random number generator’s seed. We use it with the Random
object.
For example,
import java.util.Random;
public class JavaRandomSetSeedDemo {
public static void main(String[] args) {
Random randomobj = new Random();
long seed = 100;
randomobj.setSeed(seed);
System.out.println("Random Integer value : " + randomobj.nextInt());
}
}
Output:
Random Integer value : -1193959466
Use the Random
Constructor to Set Seed for Random Number in Java
We can also call the zero-argument constructor to get a different seed every time. The seed is the beginning value of the pseudo-random number generator’s inner state, handled by the nextInt()
method.
For example,
import java.util.Random;
public class RadomSeeddemo {
public static void main(String[] args) {
Random randomobj1 = new Random(100);
System.out.println("Random number using the Constructor");
System.out.println(randomobj1.nextInt());
}
}
Output:
Random number using the Constructor
-1193959466