File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Random Class Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Random Class" Watch "Random Class" New topic

Random Class

Iqbal Ali

Joined: Aug 21, 2001
Posts: 9
When you have math.random() method to generate random numbers, why we still have a Random class? Isn't it inefficient?

-----<br />If you think education is expensive, try ignorance.
Michael Fitzmaurice
Ranch Hand

Joined: Aug 22, 2001
Posts: 168
Hi Iqbal
The java.lang.Math class has only the one method for generating randon numbers (<code>random()</code>), which returns a double value greater than or equal to 0.0 and less than 1.0. Generating random numbers is only a small part of the overall functionality it affords the programmer.
As you have rightly noticed, The Java.util.Random class can do the same thing, via the <code>nextDouble()</code> method. However, the Random class also provides further methods to generate random booleans, floats, ints, bytes, ints between a range specified by the user, and various other bits and pieces. It is therefore a specialised class dealing only with the generation of random values.
If you only need to generate a random double, then it is cheaper and easier to use the static method of the Math class. However, if you wanted to generate a series of random values of different types, then creating and using an instance of Random is a convenient way to do it.

Hope this helps.

"One good thing about music - when it hits, you feel no pain"
Bob Marley

"One good thing about music - when it hits, you feel no pain" <P>Bob Marley
I agree. Here's the link:
subject: Random Class
jQuery in Action, 3rd edition