How to set seed in random number generation in Java

Overview

This shot explains how to set seed while generating random numbers in Java.

A seed is a starting point for the random number generation. It can also be used to reproduce the sequence of random numbers.

setSeed() method of Random class

Random numbers in Java can be generated with the Random class. The Random class has the setSeed() method which is an instance method and used to set the seed for random number generation.

Syntax

public synchronized void setSeed(long seed)

Parameters

  • long seed: The initial seed value. It should be of long datatype.

Return value

This method does not return anything.

Code

In the code below, first, an instance of the Random class is created.

The seed for the instance is set using the setSeed() method on the instance by passing a long value.

Next, a random integer number and a random long number are printed as output.

import java.util.Random;
public class Main {
public static void main(String[] args)
{
Random random = new Random();
random.setSeed(12345L);
System.out.println("Random Integer Number - " + random.nextInt());
System.out.println("Random Long Number - " + random.nextLong());
}
}

Free Resources