5

In Java, why are nextInt() and nextDouble() instance methods of Random objects?

I feel that these methods should be static methods of the Random class. What is the purpose of having to instantiate a Random object to generate random integers or double values?

3 Answers 3

9

Java's Random class uses an initial seed value and a linear congruential generator as a part of its internal state to generate a sequence of random numbers. If the nextInt() and nextDouble() methods were static, they wouldn't have access to this internal storage.

From the docs:

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.

Note that this also means that if two instances of Random are created with different seeds, they'll generate two different sequences.

6

The constructor for Random lets you input a seed value, so you'd want to be able to use that with your nextFoo methods.

2
  • Thank you. Is the seed value necessary though? The Random class also has a default constructor with no parameters (that seeds based on the current time I believe). Why not just use that constructor?
    – David Faux
    May 7, 2012 at 18:36
  • 3
    @DavidFaux: It's not necessary, but it's useful if you want to seed it with specific values (for example, during testing)
    – Daenyth
    May 7, 2012 at 18:43
3

because each Random object has it's own seed that you can set

this allows each thread to have it's own Random without having to worry about efficiency issues caused by synchronization

also Math.random() lets you get a random double in the [0,1) range

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.