Random Number with Seed

  • Seed means if we are creating a Random object with specific bound or specific value , then that value which we pass to random number constructor is called as seed.
  • For example: new Random(5); here 5 is seed.
  • Note Random number Constructor just accepts Long value. Here int 5 is automatically converted to long 5l.
Class Test{
     private static Integer randomInteger() {
         return new Random(5).nextInt();
     }
     pvsm() {
         Set set = new HashSet<>();
         for(int i = 0; i < 100; i++) {
             set.add(randomInteger());
         }
         System.out.println(set.size());
     }
 }

Output: 1

Here, we expected 100 as output but it printed 1, this is because the above randomInteger method return’s same value every time. What’s happening is, when we call randomInteger value, it creates a new RandomObject but since we are passing seed value, it will always return same Integer using nextInt method().

To verify, if we add below code

Random r = new Random(5l);
syso(r.nextInt()); // Some Random Integer. Eg : 123
syso(r.nextInt()); // Some Random Integer Eg : 456
syso(r.nextInt()); // Some Random Integer Eg : 789

If we run above three println statement 100 times, everytime it will give me same Random Integer for each println. i.e first println will always print 123, second will always print 456 and third will always print 789, even if we run multiple times.

Now, if we remove this seed value from random number constructor in randomIntger method, then the size of set will be 100 because everytime it will return us diff random value.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.