How To Generate Random Number In Java (Top 4 Ways)

Java Programming Language is well rich to develop programs that generate random number. Many times, we face scenarios and project requirements to generate random numbers using Java. In this tutorial, I will explain all those techniques with sample Programs to generate random numbers in java.

Random Number Generator-Java Guide

Here are the 4 popular and secure ways to generate random numbers in Java-

  • Math.random() method: Returns a double value with a positive sign.
  • java.util.Random class: Instances of java.util.Random are threadsafe (but take care of performance).
  • ThreadLocalRandom class: It’s a child class of java.util.Random.
  • Secure Random Number Generation : The secure way…

Generate Random Number in Java


1) Math.random()

The class Math not only contains methods for generating random numbers but also to calculate exponential, logarithm, square root, and trigonometric expression. Here are some key points about Math.random() that you should note down-

  • Returns a double value with a positive sign. In one call it returns one double type number which is greater than or equal to 0.0 and less than 1.0.
  • When this method is first called, it creates a new instance or object of a pseudorandom-number generator class- Random, like this-
new java.util.Random()    // Creates New Instance of Random class

 

  • Math.random() method is synchronized to allow correct use by more than one thread. But take care of performance when many threads need to generate random numbers in bulk.
  • Because, if so many threads need to generate random numbers at a great rate, it may reduce contention for each thread to have its own random-number generator.
Structure of class Math:
java.lang.Object          // Super Class or Parent Class
     java.lang.Math       // Math Class
Definition of class Math:
public final class Math
	     extends Object
Definition of Math.random()
public static double random()
{
    //...method definition
    // ...returns double type random number
}

 

Generate Random Number using Math.random()

The static method random() of class Math, returns a positive double value, that will be greater than or equal to 0.0 and less than 1.0

Program 1: How do you generate random numbers 100 times in Java?

// Program to generate 100 random numbers in java

public class FirstRandomNumberProgram
{
    public static void main( String []arguments )
    {
        // Generating 100 Random Numbers
        for ( int i=0; i<100; i++ )
              System.out.println("\nRandom Number : " + Math.random());
    }
}

 

Output of above Random Number Generator-Java program:

Random Number : 0.19312083785977052

Random Number : 0.9392575411297682

//... 98 times more

2) java.util.Random class

An object of class java.util. Random is used to generate one or more pseudo-random numbers. But, when we instantiate the class java.util.Random, by default it’s instances are not cryptographically secure.

  • The algorithms implemented by class java.util.Random use a protected utility method that on each invocation can provide up to 32 pseudorandomly generated bits.
  • If two instances of class java.util.Random are created with the same argument, and the same sequence of method calls is made for each, they will produce and return identical sequences of numbers.
  • Instances of class java.util.Random are totally threadsafe. However, the concurrent use of the same Random instance across one or more threads may encounter highly poor performance.
  • To generate random numbers using the class java.util.Random, we need to first create an instance of this class and make use of methods such as nextInt(), nextFloat(), nextDouble(), etc. using that instance.
  • We can generate random numbers of one or more data types, eg: integers, float, double, long, booleans.
Structure of java.util.Random:
java.lang.Object
	java.util.Random
Definition of java.util.Random:
public class Random
	extends Object
		implements Serializable

Program 2: How do you generate a random number from 0 to 100 in Java?

import java.util.Random;

// Java program to generate a random number from 0 to 100 in Java?
// Make use of class java.util.Random;

public class SecondRandomNumberProgram
{
	public static void main(String args[]) 
	{ 
		// Step 1: create instance of Random class 
		Random rand = new Random(); 

		// Step 2: Generate a random integer in range 0 to 100 
		int random_int = rand.nextInt(100);

		// Step 3: Print that random integer
		System.out.println("Random Integer: " + random_int);

		// Optional: 
                // If you need 'double type' random integers,
		// Here is how-

                double random_double1 = rand.nextDouble();
                double random_double2 = rand.nextDouble();
		
                System.out.println("Random Double 1 -: " + random_double1);
		System.out.println("Random Double 2 -: " + random_double2);
	}
}

 

Output of the above Random Number Generator-Java Program
Random Integer: 41

Random Double 1 -: 0.3045839101520478

Random Double 2 -: 0.909197304072948

3) ThreadLocalRandom class

So far, we have seen a couple of ways to generate random numbers in Java that are- a static method Math.random() and instance of class java.util.Random.

However, most of the time, these won’t perform well in a multi-threaded environment.

If we talk about the performance of class Random, then in a simple way, the reason for its poor performance in a multi-threaded environment is due to a point – given that multiple threads share the same Random instance.

To address that limitation, Java introduced the java.util.concurrent.ThreadLocalRandom class in JDK 7 – for generating random numbers in a multi-threaded environment.

Multithreading is one of the essential features of Java and plays a crucial role in Java web development as well. If you already been with core Java for a decent time and trying to level up skills, drive in the Java web world and learn How to Start building scalable Java Microservices with Spring Boot and Spring Cloud by Google cloud training team (so far 4.3/5 star and 43,960+ already enrolled) Coursera.

ThreadLocalRandom class instances Generate Random Number in Java
Class Hierarchy of classes- ThreadLocalRandom and Random

Let’s see how ThreadLocalRandom performs and how can we use it with real-world example programs.

Structure of class ThreadLocalRandom:
java.lang.Object
java.util.Random
java.util.concurrent.ThreadLocalRandom
Definition of class ThreadLocalRandom:
public class ThreadLocalRandom
	                extends Random

 

Program 3: How to generate random numbers using class ThreadLocalRandom in java?
// Java program to generate random numbers using class ThreadLocalRandom ...

import java.util.concurrent.ThreadLocalRandom; 

public class ThirdRandomNumberProgram
{
    public static void main( String []arguments ) 
    { 
        // Default range is 0 to 999 for generating random numbers-
        int random_int1 = ThreadLocalRandom.current().nextInt(); 
        int random_int2 = ThreadLocalRandom.current().nextInt(); 
  
        // Printing random numbers-
        System.out.println("Random Integer : " + random_int1); 
        System.out.println("Random Integer : " + random_int2); 
  
        // Method nextDouble() would return double type Random values-
        double random_dub1 = ThreadLocalRandom.current().nextDouble(); 
        double random_dub2 = ThreadLocalRandom.current().nextDouble(); 
  
        // Printing random values (of double type)
        System.out.println("Random Double : " + random_dub1); 
        System.out.println("Random Double : " + random_dub2); 
  
        // Method nextBoolean() would return boolean type random values-
        boolean random_bool1 = ThreadLocalRandom.current().nextBoolean(); 
        boolean random_bool2 = ThreadLocalRandom.current().nextBoolean(); 
  
        // Printing random Booleans 
        System.out.println("Random Boolean : " + random_bool1); 
        System.out.println("Random Boolean : " + random_bool2); 
    } 
}

 

Output: of above Random Number Generator-Java Program:
Random Integer : 1340382768
Random Integer : -968777093
Random Double : 0.6695573904219136
Random Double : 0.6755849575303099
Random Boolean : true
Random Boolean : false

When should NOT use ThreadLocalRandom?

ThreadLocalRandom is might be a perfect solution to generate random numbers in most of the use cases, but there are some scenarios when you should avoid using ThreadLocalRandom
  • When we create instances of the class ThreadLocalRandom, by default, they are not cryptographically secure.
  • If you are working for security-sensitive applications, consider using SecureRandom for random number generation. SecureRandom output sequences are cryptographically robust.

Program 4: Secure Random Number Generation in Java

import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.SecureRandom;
 
public class FourthRandomNumberProgram
{
    public static void main(String[] args) throws NoSuchAlgorithmException, NoSuchProviderException 
    {
        SecureRandom secureRandomGenerator = SecureRandom.getInstance("SHA1PRNG", "SUN");
         
        // Getting 128 random bytes
        byte[] randomBytes = new byte[128];
        secureRandomGenerator.nextBytes(randomBytes);
         
        // Get 2 random integers
        int theRandomNumber1 = secureRandomGenerator.nextInt();
        int theRandomNumber2 = secureRandomGenerator.nextInt();
        System.out.println( "\n1st Random Number : "+ theRandomNumber1 );
        System.out.println( "\n2nd Random Number : "+ theRandomNumber2 );

        // Get 2 random integer in a particular range
        int theRandomNumInRange1 = secureRandomGenerator.nextInt(1000);
        int theRandomNumInRange2 = secureRandomGenerator.nextInt(1000);

        System.out.println( "\n1st Random No. In Range : "+ theRandomNumInRange1 );
        System.out.println( "\n2nd Random No. In Range : "+ theRandomNumInRange2 );
    }
}

 

Output: of the above program
1st Random Number : 1113009595

2nd Random Number : 656521261

1st Random No. In Range : 998

2nd Random No. In Range : 48
Note***:
In above program, I’ve passed “SHA1PRNG” and “SUN” in the getInstance() method (at statement 6). This method accepts 2 arguments- Algorithm (to generate random number) and Provider (of that algorithm).
Here the SHA1PRNG meant for SHA1 Pseudo-Random Number Generator algorithm and SUN is the provider. In short, “SHA1PRNG” is the algorithm that I want to use which was provided by “SUN”.

Conclusion 

In this tutorial, we’ve learned how to generate random numbers in java in 4 different ways. We’ve learned about Math.random() static method, java.util.Random and ThreadLocalRandom classes.

We also learned the benefits of ThreadLocalRandom over Random class in a multithreaded environment, SecureRandom over ThreadLocalRandom class in terms of security as well as performance.

And, as always, all the above Random number generator-Java programs can be found over on Github.

Found Helpful?

Hope you found this tutorial helpful! What next? Rate the article on FB || 🎁Subscribe to the weekly News-letter || Connect with me on Twitter / Facebook / LinkedIn so that you will stay informed with Tech forever. Thank you for reading it, Best of Luck !