Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Random Class

 
Iqbal Ali
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When you have math.random() method to generate random numbers, why we still have a Random class? Isn't it inefficient?
------------------
 
Michael Fitzmaurice
Ranch Hand
Posts: 168
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic