Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

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?

share|improve this question

3 Answers 3

up vote 8 down vote accepted

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.

share|improve this answer

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

share|improve this answer
    
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 '12 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 '12 at 18:43

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

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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