You are on page 1of 1

Program: How to change Random class seed value?

Description:
Some times we need to generate same random number sequence everytime we call the sequence generator
method on every call. We cannot achieve this if we use simple Random() class constructor. We need to pass seed
to the Random() constructor to generate same random sequence. You can change the seed by calling setSeed()
method. Each time you pass the same seed, you will get same random sequence. You can notice this with the
below example.

Code:
?
1
2
3 package com.java2novice.random;
4
5 import java.util.Random;
6
7 public class MyRandomSeedChange {
8
public static void main(String a[]){
9 Random rnd = new Random(40);
10 for(int i=0;i<5;i++){
11 System.out.println(rnd.nextInt(100));
12 }
System.out.println("Changing seed to change to sequence");
13
rnd.setSeed(45);
14 for(int i=0;i<5;i++){
15 System.out.println(rnd.nextInt(100));
16 }
17 System.out.println("Changing seed to change to sequence");
rnd.setSeed(50);
18 for(int i=0;i<5;i++){
19 System.out.println(rnd.nextInt(100));
20 }
21 System.out.println("Setting seed 40 to produce the previous sequence");
22 rnd.setSeed(40);
for(int i=0;i<5;i++){
23 System.out.println(rnd.nextInt(100));
24 }
25 }
26 }
27
28

You might also like