Java Random setSeed() Method



Description

The Java Random setSeed(long seed) method is used to set the seed of this random number generator using a single long seed.

Declaration

Following is the declaration for java.util.Random.setSeed() method.

public void setSeed(long seed)

Parameters

seed − This is the initial seed.

Return Value

NA

Exception

NA

Getting a Random Integer Value after Setting a Seed Example

The following example shows the usage of Java Random setSeed(long seed) method. Firstly, we've created a Random object and then using setSeed(long seed) we've set the seed and then a random number is printed using nextInt().

package com.tutorialspoint;

import java.util.*;

public class RandomDemo {
   public static void main( String args[] ) {
      
      // create random object
      Random randomno = new Random();

      // setting seed
      randomno.setSeed(20);

      // value after setting seed
      System.out.println("Object after seed: " + randomno.nextInt());
   }    
}

Output

Let us compile and run the above program, this will produce the following result.

Object after seed: -1150867590

Getting another Random Integer Value after Setting a Seed Example

The following example shows the usage of Java Random setSeed(long seed) method. Firstly, we've created a Random object and then using setSeed(long seed) we've set a new seed and then a random number is printed using nextInt().

package com.tutorialspoint;

import java.util.*;

public class RandomDemo {
   public static void main( String args[] ) {
      
      // create random object
      Random randomno = new Random();

      // setting seed
      randomno.setSeed(30);

      // value after setting seed
      System.out.println("Object after seed: " + randomno.nextInt());
   }    
}

Output

Let us compile and run the above program, this will produce the following result.

Object after seed: -1153176083

Getting another Random Integer Value after Setting a Seed Example

The following example shows the usage of Java Random setSeed(long seed) method. Firstly, we've created a Random object and then using setSeed(long seed) we've set a new seed and then a random number is printed using nextInt().

package com.tutorialspoint;

import java.util.*;

public class RandomDemo {
   public static void main( String args[] ) {
      
      // create random object
      Random randomno = new Random();

      // setting seed
      randomno.setSeed(40);

      // value after setting seed
      System.out.println("Object after seed: " + randomno.nextInt());
   }    
}

Output

Let us compile and run the above program, this will produce the following result.

Object after seed: -1170874532
java_util_random.htm
Advertisements