234k views
2 votes
How does psuedo random and seeds work in java?

User Truman
by
7.8k points

1 Answer

5 votes

Final answer:

In Java, a pseudo-random number generator (PRNG) is used to generate random numbers. This type of generator uses an algorithm to produce a sequence of seemingly random numbers. However, the sequence is actually determined by an initial seed value.

Step-by-step explanation:

In Java, a pseudo-random number generator (PRNG) is used to generate random numbers. This type of generator uses an algorithm to produce a sequence of seemingly random numbers. However, the sequence is actually determined by an initial seed value. The same seed will always generate the same sequence of numbers.



When using a PRNG in Java, you can set the seed value by calling the setSeed() method of the Random class. This allows you to have control over the sequence of random numbers generated. For example, if you set the seed to 123, the PRNG will always generate the same sequence of numbers.



Here's an example of how to use the Random class and set the seed:



  1. import java.util.Random;
  2. public class RandomSeedExample {
  3. public static void main(String[] args) {
  4. Random rand = new Random();
  5. rand.setSeed(123);
  6. for (int i = 0; i < 5; i++) {
  7. System.out.println(rand.nextInt(100));
  8. }
  9. }
  10. }



This program will always output the same sequence of 5 random numbers because the seed is set to 123.

User Dmytro Boichenko
by
8.1k points