Search code examples
javarandom

Why is Random() not behaving as expected?


I've been scratching my head over this for long enough, It's time for the big guns:

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

why does the above seem to print -1157793070, always?


Solution

  • It is because you define a custom seed that is always the same with each run. From the JavaDoc:

    The seed is the initial value of the internal state of the pseudorandom number generator which is maintained by method {@link #next}.

    This is particularly useful for running tests.