Random number generator in java

In this post we are going to learn random number generator in java.

Generating random numbers in java is common interview question. Let’s see how to easily generate random numbers in java using few methods,

Getting random numbers in java

math.random java

To begin with, let’s look at math.random(). It does not take any parameters and returns a double value with a positive sign greater than or equal to 0 and less than 1.

Also read – quicksort in java

Output will never be one, it may be equal to zero though that’s very very unlikely. They are chosen pseudo randomly with the uniform distribution in that range. So it’s not a perfect random generator, but it’s close.

Let’s see java program to generate random number,

public class RandomNumberInJava
{ 
   public static void main(String[] args) 
   {
      // output will be of DataType double 
      System.out.println(Math.random()); 
      System.out.println(Math.random());
   }
}

Output:

random number generator in java


java.util.random example

In the below java program we are creating instance of class Random. Then instance methods namely nextFloat(), nextBoolean() etc., are invoked.

import java.util.Random;

public class JavaRandomClass 
{ 
   public static void main(String[] args) 
   {
      Random rd = new Random();
      // creating random integers
      int randInt = rd.nextInt();
      System.out.println(randInt);

      // creating random doubles
      double randDouble = rd.nextDouble();
      System.out.println(randDouble);

      // creating random booleans
      boolean randBool = rd.nextBoolean();
      System.out.println(randBool);

      // creating random floats
      float randFloat = rd.nextFloat();
      System.out.println(randFloat);
   }
}

Output:

1786368858
0.9911121092414749
false
0.15194857


java.util.concurrent.ThreadLocalRandom

A random number generator isolated to the current thread. Like the global Random generator used by the Math class, a ThreadLocalRandom is initialized with an internally generated seed that may not otherwise be modified.

This class was introduced in java 1.7. Now let’s see java program to generate random number using above class.

import java.util.concurrent.ThreadLocalRandom;

public class ThreadLocalRandomDemo 
{
   public static void main(String[] args)
   {
      // random integers
      int randomInteger = ThreadLocalRandom.current().nextInt(); 
      System.out.println(randomInteger); 

      // random doubles
      double randomDouble = ThreadLocalRandom.current().nextDouble(); 
      System.out.println(randomDouble); 

      // random booleans
      boolean randomBoolean = ThreadLocalRandom.current().nextBoolean();
      System.out.println(randomBoolean);
   }
}

Output:

951227305
0.9477534236023137
false


Reference – oracle docs