Java: Can (new Random()).nextInt(5) always return the same number?

java, random

Solution

The javadoc for java.util.Random is clear:

If two instances of Random are created with the same seed, and the same sequence of method calls is made for each, they will generate and return identical sequences of numbers.

The default constructor is also clear:

Creates a new random number generator. This constructor sets the seed of the random number generator to a value very likely to be distinct from any other invocation of this constructor.

In other words, no guarantees.

If you need a more random algorithm, use java.security.SecureRandom.

Problem

Sometimes this piece of code always returns the same number (and sometimes it works fine): ``` (new Random()).nextInt(5) ``` I have suspicions where the problem is - it probably always creates a new Random with the same seed. So what would be the best solution: - create a static var for Random() and use it instead. - use Math.random() * 5 (looks like it uses a static var internally) or something else? I don't need anything fancy just something that looks random. Also it would be helpful if someone can explain why the original code sometimes works and sometimes it doesn't. Thanks.

Original source

Related problems