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

Tags: java random
By : serg
Source: Stackoverflow.com
Question!

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.

By : serg


Answers

The Javadoc for Random isn't explicit about this, but the seed it uses is probably dependent on the current system time. It does state the random numbers will be the same for the same seed. If you use the call within the same millisecond, it will use the same seed. The best solution is probably to use a static Random object and use it for subsequent calls to the method.

By : Jorn


The best way to approximate uniform distribution is to use the static method Random.nextInt(n) to produce integers in the range [0, n-1] (Yes, n is excluded). In your particular example, if you want integers in the range 0 to 5, inclusive, you would call Random.nextInt(6).



This video can help you solving your question :)
By: admin