GeeCON Prague 2014*
The moose likes Java in General and the fly likes diff. bet. Math.random() and java.util.random Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Java in General
Bookmark "diff. bet. Math.random() and java.util.random" Watch "diff. bet. Math.random() and java.util.random" New topic
Author

diff. bet. Math.random() and java.util.random

Augustine Kanagasabapathy
Greenhorn

Joined: Sep 23, 2003
Posts: 2
hi
Could any one tell me whether any practical diff. bet the Math.random and java.util.Random class. I understand that Math.random() is a static method & it is shared by all who r accessing it. But using java.util.Random, i can create new instance every time. any other difference???
thanx in adv.
luv,
Augg
Wayne L Johnson
Ranch Hand

Joined: Sep 03, 2003
Posts: 399
I checked the source code, and the "Math.random()" method does a lazy (on-demand) instantiation of a "java.util.Random" instance the first time it's invoked. Then it simply calls the "nextDouble()" method. So Math.random() is simply a wrapper around "java.util.Random".
Augustine Kanagasabapathy
Greenhorn

Joined: Sep 23, 2003
Posts: 2
Hi,
Thanx for ue reply. I do not understand what u mean by the word on-demand instantiation. When i say "new A()", then JVM has to create a new instance of A, right??? Could u pls explain this in detail???
luv,
Augg
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24187
    
  34

He just means the instance of Random isn't created until the first time Math.random() is called; like


[Jess in Action][AskingGoodQuestions]
 
GeeCON Prague 2014
 
subject: diff. bet. Math.random() and java.util.random