In this code:
Random random = new Random(441287210);
for(int i=0;i<10;i++)
System.out.print(random.nextInt(10)+" ");
}
The output is 1 1 1 1 1 1 1 1 1 1, every time.
Why is this? Isn’t Random supposed to be… well… random? I thought that the Random class use System.nanoTime, so the output should be generally random. Can someone please explain?
The values generated by
Randomclass are pseudo-random: they are created using a deterministic algorithm, based on seed value. Typically (if you use parameterless constructor, for example) the seed is initialized using current time, which is obviously a unique value. Hence a unique, ‘random’ sequence is generated.Here you are using a constant seed value which doesn’t change between executions of your code. Therefore you always get the same sequence. It just happens that this sequence is
1 1 1 1 1 1 ...for this particular seed.