-5

Halo everyone I've started learning java recently and i have this question what does a Random obj seed stands for ?? what does it mean ? and the difference between

Random r1 = new Random(); Random r2 = new Random(3);

2 Answers2

1

It's not just a java thing.

It's very hard to let a computer generate a real random number. Your computer needs to perform a complex unpredicatble calculation. Your seed value will act as an input for these calculations.

A lot of systems will use a timestamp as a seed. Because that's a value that will be different every time you run it. But let's say you do specify a seed, and that you use the same seed multiple times:

    Random rnd = new Random(10);
    System.out.println(rnd.nextInt());
    System.out.println(rnd.nextInt());
    System.out.println(rnd.nextInt());

    // do it again with the same seed
    rnd = new Random(10);
    System.out.println(rnd.nextInt());
    System.out.println(rnd.nextInt());
    System.out.println(rnd.nextInt());

This code will print the same 3 values 2 times.

Output:

-1157793070
1913984760
1107254586
-1157793070
1913984760
1107254586

So, if you reuse a seed value, it will generate the same numbers.

bvdb
  • 22,839
  • 10
  • 110
  • 123
0

By

 Random r1 = new Random();

you'll get different sequences of returned numbers between app invocations even if calling same sequences of r1 methods with same arguments. But if your provide particular seed number, sequences of returned results will be the same (of course, only if r2 will be invoked in same sequence of methods and arguments).

This feature is often very helpful in testing, if you perform operations on some randomly generated dataset--it allows to generate the same dataset on each test run.

Alex Salauyou
  • 14,185
  • 5
  • 45
  • 67