4 Ways to Generate Random Numbers in Java


There are different ways and classes in the JDK allowing you to generate random numbers, using some built-in methods:

  • ThreadLocalRandom
  • SecureRandom
  • Random
  • Math.random

the algorithm used in RNG (random number generator ) works on the seed value. If not provided, seed value is created from

Pseudorandom number generator

A pseudorandom number generator (PRNG), also known as a deterministic random bit generator DRBG, is an algorithm for generating a sequence of numbers that approximates the properties of random numbers. The sequence is not truly random in that it is completely determined by a relatively small set of initial values, called the PRNG's state, which includes a truly random seed.

 

Let’s see some examples of those 4 RNG:

 

SecureRandom

Random class instances are not recommended for security sensitive applications. in those cases it’s better to use java.security.SecureRandom .

Below method explains how to use this class to generate random numbers:

static void generateRandomNumbers_SecureRandom() {

      SecureRandom secureRandom = new SecureRandom();

      // Generate 5 random integers from 0 to 50(exclusiv)
      System.out.println("5 Random integers  from 0 to 1000");

      for(int i=0; i<5 ; i++){
          System.out.println(secureRandom.nextInt(1000) );
      }


      // Generate 5 random booleans
      System.out.println("5 Random floats");

      for(int i=0; i<5 ; i++){
          System.out.println( secureRandom.nextFloat());
      }
  }

Output:
5 Random integers  from 0 to 1000
633
216
110
1
160

5 Random floats
0.15990353
0.2535593
0.630384
0.20399791
0.28208458

 

 

java.util.Random

This is the superclass of both ThreadLocalRandom and SecureRandom.

To generate random numbers with this class

  • We need to create an instance of this class 
  • Then invoke methods such as nextInt(), nextDouble(), nextLong() etc using that same instance.
  • These methods accept as argument an int parameter allowing us to place an upper bound (excluded) on the range of the numbers to be generated.
void generateRandomNumbers(){

    // create instance of Random class
    Random rand = new Random();

    // Generate 5 random integers from 0 to 100
    System.out.println("5 Random integers  from 0 to 100");

    for(int i=0; i<5 ; i++){
         System.out.println( rand.nextInt(100));
    }

    // Generate 5 Random doubles without an upper bound
    System.out.println("5 Random doubles without an upper bound");

    for(int i=0; i<5 ; i++){
         System.out.println( rand.nextDouble());
    }
}




Output:

5 Random integers  from 0 to 100
96
25
3
96
69

5 Random doubles without an upper bound
0.7185403429212524
0.6472626238056732
0.21925358812200402
0.8406620047634145
0.20326267155556865

 

 

Math.random

 a static method which generates doubles evenly distributed between 0.0 (inclusive) and 1.0 (exclusive).

static void generateRandomNumbers_MathRandom(){
    System.out.println("5 Random doubles with Math.random()  ");
    // Generate 5 random doubles
    for(int i=0; i<5 ; i++){
           System.out.println( Math.random());
    }
}

Output:
5 Random doubles with Math.random()
0.8568392662120566
0.7939697894310086
0.3942350123781264
0.16284041302320518
0.5301991774232604

 

 

ThreadLocalRandom

This is ma recommended way to generate random numbers. ThreadLocalRandom was introduced in java 1.7 

Like java.util.Random, this class allows generating random numbers of type integers, doubles, booleans… but ThreadLocalRandom gives the possibility to specify the upper bound, but also the origin (least value the can be returned).

The lower bound is included, but the upper bound is excluded

 

note the static factory method for getting an object;

 

static void generateRandomNumbers3(){

       // Generate 5 random integers from 0 to 50(exclusiv)
       System.out.println("5 Random integers  from 0 to 50");

       for(int i=0; i<5 ; i++){
         System.out.println( ThreadLocalRandom.current().nextInt(0,50));
       }

       System.out.println("5 Random booleans");

       // Generate 5 random booleans
       for(int i=0; i<5 ; i++){
            System.out.println( ThreadLocalRandom.current().nextBoolean());
       }
 }


Output:

5 Random integers  from 0 to 50
31
27
45
40
45

5 Random booleans
false
false
true
true
true

 

Best practices

 

My recommendation goes to ThreadLocalRandom, for the multiple possibilities provided.

Don’t forget:

  • To generate a series of random numbers as a unit, you need to use a single object. Do not create a new object for each new random number.
  • When methods in these classes accept a lower and upper bound, the lower bound is inclusive and the upper bound is exclusive.

 

Recent Posts