Random Class in Java

Introduction

Java Random class is used to generate a stream of pseudorandom numbers. In this article, we will learn about the Java Random class, its methods, and constructors provided in the Java programming language.

What is Random Class in Java?

Random class is part of java.util package. An instance of the Java Random class is used to generate random numbers. This class provides several methods to generate random numbers of type integer, double, long, float, etc. The random number generation algorithm works on the seed value. If not provided, the seed value is created from system nano time. If two Random instances have the same seed value, then they will generate the same sequence of random numbers.

Java Random class is thread-safe. However, in the multithreaded environment, it's advised to use java.util.concurrent.ThreadLocalRandom class. Random class instances are not suitable for security-sensitive applications; better to use java.security.SecureRandom in those cases.

java.lang.Object
    java.util.Random

The algorithms implemented by the Random class use a protected utility method that can supply up to 32 pseudorandomly generated bits on each invocation. This class provides various method calls to generate different random data types such as float, double, and int.

Random class declaration

public class Random
    extends Object
    implements Serializable

Basic Random number generator

Many times we need to generate a sequence of numbers. It is not a problem to generate a sequence of numbers. But sometimes, we need to generate random numbers. In java, we can generate random numbers by using the Random class. By using a Random class, we can generate random integers, long numbers, and double values.

The complete program for generating a random number is listed below.

import java.util.Random;  
public class RandomNumberGenerator {  
    public static void main(String a[]){  
        Random rand = new Random();  
        System.out.println("Random Integers:");  
        System.out.println(rand.nextInt());  
        System.out.println(rand.nextInt());  
        System.out.println(rand.nextInt());  
        System.out.println("Random Double Numbers:");  
        System.out.println(rand.nextDouble());  
        System.out.println(rand.nextDouble());  
        System.out.println(rand.nextDouble());  
        System.out.println("Random Long Numbers:");  
        System.out.println(rand.nextLong());  
        System.out.println(rand.nextLong());  
        System.out.println(rand.nextLong());  
    }  
} 

The above program generates the following output.

random-number-generator-output

Constructors of Random class


Random()

Creates a new random number generator. Its seed is initialized to a value based on the current time.

Syntax

public Random()  
{ 
    this(System.currentTimeMillis());  

}

The complete program of the Random class using the Random() constructor is listed below.

import java.util.Random;

public class RandomClassExample1 {
    public static void main(String[] args) {
        Random random = new Random();
        System.out.println(random.nextBoolean());
        System.out.println(random.nextDouble());
        System.out.println(random.nextFloat());
        System.out.println(random.nextInt());
        System.out.println(random.nextInt(20));
    }
}

The above program generates the following output.

random-class-example1-output

Random(long seed)

Creates a new random number generator using a specified seed.

Syntax

public Random(long seed)
{
    setSeed(seed);
} 

The complete program of Random class using Random(long seed) constructor is listed below.

import java.util.Random;    
public class RandomClassExample2 {    
    public static void main(String[] args) {    
        Random random = new Random(100);    
        System.out.println("Using Random(long seed)Constructor");    
        System.out.println(random.nextInt());    
    }    
}   

The above program generates the following output.

Methods of Random Class


1) java.util.Random.next() Method

The next(int bits) method is used to generate the next pseudorandom number. The java.util.Random.next() method uses the bit parameter, which is random bits. The method call returns the next pseudorandom value from this random number generator sequence.

The complete program of java.util.Random.next() method is listed below.

import java.util.Random;    
public class RandomClassExample3 {    
    public static void main(String args[]) {    
        // create random object    
        Random randomno = new Random();    
        // get next next pseudorandom value    
        int value = randomno.nextInt();    
        // check the value    
        System.out.println("Value is: " + value);    
    }    
}   

The above program generates the following output.

randomclass-example3-output

2) java.util.Random.nextBoolean() Method

The nextBoolean() method is used to get the next pseudorandom, uniformly distributed boolean value from this random number generator's sequence. The java.util.Random.nextBoolean() method returns a boolean value.

The complete program of java.util.Random.next() method is listed below.

import java.util.Random;    
public class RandomClassExample4 {    
    public static void main( String args[] ) {    
        // create random object    
        Random randomno = new Random();    
        // get next next boolean value    
        boolean value = randomno.nextBoolean();    
        // check the value    
        System.out.println("Value is: " + value);    
    }    
}   

The above program generates the following output.

randomclass-example4-output

3) java.util.Random.nextBytes(byte[] bytes) Method

The nextBytes(byte[] bytes) method is used to generate random bytes and places them into a user-supplied byte array. The java.util.Random.nextBytes(byte[] bytes) uses the bytes as a parameter which is the non-null byte array in which to put the random bytes.

The complete program of java.util.Random.nextBytes() method is listed below.

 

import java.util.Random;    
public class RandomClassExample5 {    
    public static void main( String args[] ) {    
        // create random object    
        Random randomno = new Random();    
        // create a byte array    
        byte[] nbyte = new byte[30];    
        // put the next byte in the array    
        randomno.nextBytes(nbyte);    
        // check the value of the array    
        System.out.println("Value of byte array: " + nbyte);    
    }    
}   

The above program generates the following output.

randomclass-example5-output

4) java.util.Random.nextDouble() Method

The nextDouble() method is used to get the next pseudorandom, uniformly distributed double value between 0.0 and 1.0 from this random number generator's sequence.

The complete program of java.util.Random.nextDouble() method is listed below.

import java.util.Random;    
public class RandomClassExample6 {    
    public static void main( String args[] ) {    
        // create random object    
        Random randomno = new Random();    
        // check next double value    
        System.out.println("Next double value: " + randomno.nextDouble());    
    }    
}   

The above program generates the following output.

randomclass-example6-output

5) java.util.Random.nextFloat() Method

The nextFloat() method is used to get the next pseudorandom, uniformly distributed float value between 0.0 and 1.0 from this random number generator's sequence.

The complete program of java.util.Random.nextFloat() method is listed below.

import java.util.Random;    
public class RandomClassExample7 {    
    public static void main( String args[] ) {    
        // create random object    
        Random randomno = new Random();    
        // check next float value    
        System.out.println("Next float value: " + randomno.nextFloat());    
    }    
}   

The above program generates the following output.

randomclass-example7-output

6) java.util.Random.nextGaussian() Method

The nextGaussian() method is used to get the next pseudorandom, Gaussian ("normally") distributed double value with mean 0.0 and standard deviation 1.0 from this random number generator's sequence.

The complete program of java.util.Random.nextGaussian() method is listed below.​​​​​​​

import java.util.Random;    
public class RandomClassExample8 {    
    public static void main( String args[] ) {    
        // create random object    
        Random randomno = new Random();    
        // check next Gaussian value      
        System.out.println("Next Gaussian value: " + randomno.nextGaussian());    
    }    
}   

The above program generates the following output.

randomclass-example8-output

7) java.util.Random.nextInt() Method

The nextInt() method is used to get the next pseudorandom, uniformly distributed int value from this random number generator's sequence.

The complete program of java.util.Random.nextInt() method is listed below.​​​​​​​

import java.util.Random;  
public class RandomClassExample9 {  
    public static void main(String args[]) {  
        // create random object  
        Random randomno = new Random();  
        // check next int value  
        System.out.println("Next int value: " + randomno.nextInt());  
    }  
} 

The above program generates the following output.

8) java.util.Random.nextInt(int n) Method

The nextInt(int n) method is used to get a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive), drawn from this random number generator's sequence. The java.util.Random.nextInt(int n) uses the n as a parameter. This is the bound on the random number to be returned. Must be positive.

Exception: IT throws the IllegalArgumentException if n is not positive.

The complete program of java.util.Random.nextInt(int n) method is listed below.​​​​​​​

import java.util.Random;  
public class RandomClassExample10 {  
    public static void main( String args[] ) {  
        // create random object  
        Random randomno = new Random();  
        // check next int value  
        System.out.println("Next int value: " + randomno.nextInt(10000));  
    }  
} 

The above program generates the following output.

randomclass-example10-output

9) java.util.Random.nextLong() Method

The nextLong() method is used to return the next pseudorandom, uniformly distributed long value from this random number generator's sequence.

The complete program of java.util.Random.nextLong() method is listed below.​​​​​​​

import java.util.Random;  
public class RandomClassExample11 {  
    public static void main( String args[] ) {  
        // create random object  
        Random randomno = new Random();  
        // get next long value  
        long value = randomno.nextLong();  
        // check the value  
        System.out.println("Long value is: " + value);  
    }  
} 

The above program generates the following output.

randomclass-example11-output

10) java.util.Random.setSeed(long seed) Method

The setSeed(long seed) method is used to set the seed of this random number generator using a single long seed. The java.util.Random.setSeed(long seed) method uses a parameter as a seed, which is the initial seed.

The complete program of java.util.Random.setSeed(long seed) method is listed below.​​​​​​​

import java.util.Random;  
public class RandomClassExample12 {  
    public static void main( String args[] ) {  
        // create random object  
        Random randomno = new Random();  
        // setting seed  
        randomno.setSeed(20);  
        // value after setting seed  
        System.out.println("Object after seed: " + randomno.nextInt());  
    }  
} 

The above program generates the following output.

randomclass-example12-output

What is a seed in Random number generator Java?

The seed is the initial value of the internal state of the pseudorandom number generator, which is maintained by method next(int). Creates a new random number generator using a single long seed.

The invocation of new Random(seed) is equivalent to.

Random rnd = new Random();
rnd.setSeed(seed);

How to change the Random class seed value?

Sometimes we need to generate the same random number sequence every time we call the sequence generator method on every call. We cannot achieve this if we use simple Random() class constructor. We need to pass the seed to the Random() constructor to generate the same random sequence. You can change the seed by calling the setSeed() method. You will get the same random sequence each time you pass the same seed.

The complete program shows the process of changing the seed value in the Random class.​​​​​​​

import java.util.Random;  
public class RandomClassExample13 {  
    public static void main(String a[]) {  
        Random rnd = new Random(40);  
        for (int i = 0; i < 3; i++) {  
            System.out.println(rnd.nextInt(100));  
        }  
        System.out.println("Changing seed to change to sequence");  
        rnd.setSeed(45);  
        for (int i = 0; i < 3; i++) {  
            System.out.println(rnd.nextInt(100));  
        }  
        System.out.println("Changing seed to change to sequence");  
        rnd.setSeed(50);  
        for (int i = 0; i < 3; i++) {  
            System.out.println(rnd.nextInt(100));  
        }  
        System.out.println("Setting seed 40 to produce the previous sequence");  
        rnd.setSeed(40);  
        for (int i = 0; i < 3; i++) {  
            System.out.println(rnd.nextInt(100));  
        }  
    }  
} 

The above program generates the following output.

randomclass-example13-output

Summary

In this article, we learned about the Random class, its methods and the constructors of the Random Class in Java programming language, and how to use the Random class in the Java programs.