Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't Random class static?

Tags:

In Java we have static class Math. You don't need to create its objects so its static. Another one is Random class. We don't need to create its instances so why isn't it static too? My classes I often use random numbes and get mad when have to create field rand in every class to generate random numbers. So why isn't it static?

like image 449
Michał Tabor Avatar asked Jan 20 '13 12:01

Michał Tabor


People also ask

Is random class static?

Note that just like all other methods of the Math class, Math. random() is a static method so you can call it directly on the Math class without needing an object. It returns a value of type double .

What is random static?

Random Static is a New Zealand based science fiction publisher. This site provides information about our publications, and online shopping services for various imports as well as our own titles. All prices are in New Zealand dollars.

Is Java random actually random?

These created values are not truly "random" because a mathematical formula is used to generate the values. The "random" numbers generated by the mathematical algorithm are given a starting number (called the "seed") and always generates the same sequence of numbers.

Why are the random numbers Java generates not really random?

Random number generators are really only pseudo-random. That is, they use deterministic means to generate sequences that appear random given certain statistical criteria. The Random(long seed) constuctor allows you to pass in a seed that determines the sequence of pseudo-random numbers.


1 Answers

The Random class has state, including where it is in its sequence, as the values produced are not truly random, just a pseudo-random sequence.

This can be demonstrated by initialising two instances with the same seed.

Random a = new Random(123); Random b = new Random(123); for (int i = 0; i < 5; i++) {     System.out.println(a.nextInt() + "," + b.nextInt()); } 

Output

-1188957731,-1188957731 1018954901,1018954901 -39088943,-39088943 1295249578,1295249578 1087885590,1087885590 

If you create with the default constructor Random(), then the seed is initialized based on the current time in nanoseconds + a static counter, which means different instances are very likely to have different sequences.

like image 120
Adam Avatar answered Dec 17 '22 09:12

Adam