Java Random.setSeed() – Examples

In this tutorial, we will learn about the Java Random.setSeed() method, and learn how to use this method to set seed for the Random class object, with the help of examples.

setSeed(seed)

Random.setSeed() method sets the seed of this random number generator using a single long seed.

ADVERTISEMENT

Syntax

The syntax of setSeed() method is

Random.setSeed(long seed)

where

ParameterDescription
seedThe initial seed for the Random number generator.

Returns

The method returns void.

Example 1 – setSeed(seed)

In this example, we will create a Random class object and set the seed for this Random object.

Java Program

import java.util.Random;

public class Example {  
	public static void main(String[] args) {  
		Random random = new Random(); 
  
		long seed = 20;  
		random.setSeed(seed);
		System.out.println("The seed is set for the random object.");
		
		System.out.println("Next Random Int : "+random.nextInt());  
    }  
}

Output

The seed is set for the random object.
Next Random Int : -1150867590

Example 2 – setSeed(seed) – Multiple Runs

In this example, we will see how setting a seed to Random class object effects the generation of random numbers. We will print next random integers using nextInt() method. For a given seed, the sequence of random numbers generated, for each run will remain same.

Java Program

import java.util.Random;

public class Example {  
	public static void main(String[] args) {  
		Random random = new Random(); 
  
		long seed = 20;  
		random.setSeed(seed);
		
		for(int i = 0; i < 10; i++) {
			System.out.println(random.nextInt());
		}
    }  
}

Run #1

-1150867590
-1704868423
884779003
-29161773
-885414485
-1791719506
700408466
-1654940986
665796387
-1584522320

Run #2

-1150867590
-1704868423
884779003
-29161773
-885414485
-1791719506
700408466
-1654940986
665796387
-1584522320

Conclusion

In this Java Tutorial, we have learnt the syntax of Java Random.setSeed() function, and also learnt how to use this function with the help of examples.