SpringLearner - 1 year ago 39

Java Question

There are 2 constructors of

`Random`

`public Random()`

`public Random(long seed)`

The description for the second constructor as per oracle states as

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 next(int).

I did not understand it completely. And I did not find any articles/book which clearly explains

Can any one explain please?

Answer Source

A pseudorandom number generator works by repeatedly generating a new number based on the one it has previously generated. That means that if you always have the same *first* "random" number, and you use the same pseudorandom number generator to generate the second, you'll always have the same *second* "random" number as well.

The first `Random`

constructor constructs a pseudorandom number generator with a nondeterminate seed (first number in the sequence), so you'll almost always end up with a different sequence of "random" numbers. The second `Random`

constructor constructs a pseudorandom number generator with *whatever seed you want*, so if you give it the same seed, you'll always get the same sequence.

Here's an example. If you create a `Random`

like this:

```
Random yourRandom = new Random();
```

it will start off with some seed. That seed could be 42, 121, 3810, whatever. You can never be sure when you create it. All the random numbers it *generates* are based off of that seed, and so since it nearly always uses a different seed, you'll nearly always get different "random" numbers out of it.

On the other hand, if you create a `Random`

like this instead:

```
Random yourOtherRandom = new Random(36);
```

all the numbers `yourOtherRandom`

generates will be calculated starting from 36. Since the first number (36) is the same, and the second number is calculated from the first, etc., everything `yourOtherRandom`

generates will be the same every time you run your program.