-4

I want to know why the numbers appearing in the first column will change each time the code is run. The numbers in the second column will always be the same. (83 51 77 90 96 58 35 38 86 54)?

 Random randomGenerator = new Random(); 
 Random otherGenerator = new Random(123); 
 for(int i = 0; i < 10; i++) {
     int number1 = 1 + randomGenerator.nextInt(100);
     int number2 = 1 + otherGenerator.nextInt(100); 
     System.out.println("random numbers "+number1+" " +number2);
 }
Physics3067
  • 57
  • 1
  • 6
  • the numbers in the second column are not always the same.... – Ousmane D. Feb 28 '17 at 21:02
  • 1
    @OusmaneDiaw - I think OP means that the code generates the same sequence of values in the second column each time this code is run, not that the second column is filled with a single value. – Ted Hopp Feb 28 '17 at 21:03
  • @TedHopp I see. Description was a little bit confused but i get it now. – Ousmane D. Feb 28 '17 at 21:04

2 Answers2

4

This happens because the Random used for the second column is seeded with a constant 123, while the one for the first column has a seed that varies each time the code is executed.

Note that the values produced by Random are not truly random; they are completely determined by the seed.

Ted Hopp
  • 232,168
  • 48
  • 399
  • 521
0

The doc says:

Creates a new random number generator using a single long seed. The seed is the initial value of the internal state of the pseudorandom number generator which is maintained by method

You have fixed the initial state of the 2nd generator is fixed and it is from the seed that the next random numbers are generated.

On the other side, if you used System.nanoTime() to generate the seed, you would see each time your generator creates different random numbers.

See: https://docs.oracle.com/javase/7/docs/api/java/util/Random.html#Random(long)

Adonis
  • 4,670
  • 3
  • 37
  • 57