Java Random setSeed() Method
Example
Set the same seed two times, and get the same random number both times:
import java.util.Random;
public class Main {
public static void main(String[] args) {
Random rand = new Random();
rand.setSeed(42);
int first = rand.nextInt(100);
rand.setSeed(42);
int second = rand.nextInt(100);
System.out.println("Same number both times? " + (first == second));
}
}
Definition and Usage
The setSeed() method sets the seed of the Random object. The seed is the start value that the object uses to calculate its random numbers.
The same seed always gives the same numbers, in the same order. This is useful when you test a program, because each run gives the same result. You can also set the seed when you create the object, with new Random(42). Two Random objects with the same seed give the same numbers.
Tip: Do not set a fixed seed when you want new numbers each time, for example in a game. A Random object without a seed gets a different seed each time the program runs.
Syntax
public void setSeed(long seed)
Parameter Values
| Parameter | Description |
|---|---|
| seed | Required. The start value, a long number. |
Related Pages
Java How To Generate Random Numbers
❮ Random Methods