How to Generate Random Numbers in JAVA?

How to Generate Random Numbers in JAVA?

Generating Random numbers in Java made easier!!

Getting Started!!

There are three ways in Java to generate random numbers using the method and classes -

  • Using the random() Method

  • Using the Random Class

  • Using the ThreadLocalRandom Class

There is one more method ints() Method that is a part of JAVA 8 which we will talk about at the end of the Blog.

Before we start, here is the link to the repository that contains all the source code. Feel free to Check it out!!

Using the random() method of Math class

For this approach, we must first import the "java.lang.Math" class. Then we can simply invoke the "Math.random()" function to generate a random number. Some key things to keep in mind regarding this function:

  • It is a static method of Math class. We can invoke it directly.

  • It generates only double-type random numbers greater than or equal to 0.0 and less than 1.0.

Here is an example for you!!

import java.lang.Math;

public class randomExample1{
    public static void main(String[] args)
    {
        System.out.println("1st Random number is: "+ Math.random());
        System.out.println("2nd Random number is: "+ Math.random());
        System.out.println("3rd Random number is: "+ Math.random());
        System.out.println("4rd Random number is: "+ Math.random());
    }


}

Take a look at the Output of this Code Block

This method looks fine but what if we want to generate a random number that lies in a specified range? Well, we can do that by using this cool formula "Math.random() * (max - min + 1) + min ". We can specify the upper limit (max) and lower limit (min) and this formula will do the rest for us. Let's give it a try. We will print a random that lies in the range of 100-200. I have added another println statement just to state the difference.

import java.lang.Math;

public class randomExample2{
    public static void main(String[] args)
    {
        int max=200;
        int min=100;

        System.out.println("1st Random number is: "+ Math.random() * ((max -    min + 1) + min) +"\n" );
        System.out.println("2nd Random number is: "+ Math.random());

    }
}

Take a look at the Output of this Code Block

Using the Random class

Another way to generate a random number is to use the Java Random class of the java.util package. It generates a stream of pseudorandom numbers. We can generate a random number of any data type, such as integer, float, double, Boolean, long.

(IMP: we were only able to generate a random number of "double" type using random method of Math class)

For using this approach, First, import the class java.util.Random. Then, Create an object of the Random class. Then, you can Invoke any of the following methods:

  • nextInt(int bound)

  • nextInt()

  • nextFloat()

  • nextDouble()

  • nextLong()

  • nextBoolean()

IMP: The nextInt(int bound) method accepts a parameter bound (upper) that must be positive. It generates a random number in the range 0 to bound-1.The nextDouble() and nextFloat() method generates random value between 0.0 and 1.0.

import java.util.Random;

public class RandomExample3 {
    public static void main(String[] args) {

        Random randomNumber=new Random();
        int x=randomNumber.nextInt(100);
        int y=randomNumber.nextInt(46);

        System.out.println("Randomly Generated Numbers: \n");
        System.out.println("First Time: "+ x);
        System.out.println("Second Time: "+ y);


        double p=randomNumber.nextDouble();    
        double q=randomNumber.nextDouble();

        System.out.println("Randomly Generated Numbers-DOUBLE: \n");
        System.out.println("First Time: "+ p);
        System.out.println("Second Time: "+ q);

        boolean a=randomNumber.nextBoolean();
        boolean b=randomNumber.nextBoolean();

        System.out.println("Randomly Generated Numbers-Boolean: \n");
        System.out.println("First Time: "+ a);
        System.out.println("Second Time: "+ b);
    }

}

Take a look at the Output of this Code Block

Using the ThreadLocalRandom Class

The ThreadLocalRandom class is defined in java.util.concurrent package. It is initialized with an internally generated seed, the same as the random generator of the Math class. It cannot be modified and is used in the following format:

ThreadLocalRandom.current().nextX(...)  

where X is Int, Long, etc

We can generate a random number of any data type, such as integer, float, double, Boolean, long using ThreadLocalRandom Class. To generate random numbers using this class, first import the class by using java.util.concurrent.ThreadLocalRandom. Then Invoke the corresponding method for which you want to generate numbers randomly.

  • nextInt()

  • nextDouble()

  • nextLong()

  • nextFloat()

  • nextBoolean()

We can also use these methods to specify a boundary and/or a range.

  • nextInt(int bound) or nextInt(int origin,int bound)

  • nextDouble(int bound) or nextDouble(int origin, int bound)

  • nextLong(int bound) or nextLong(int origin, int bound)

Here is a comprehensive example that explains this approach!!

import java.util.concurrent.ThreadLocalRandom;   

public class RandomExample4  
{   
public static void main(String args[])   
{     
int a = ThreadLocalRandom.current().nextInt();   
int b = ThreadLocalRandom.current().nextInt(); 

// Print random integer values  
System.out.println("Randomly Generated Integer Values:");  
System.out.println(a);   
System.out.println(b);   

// Generate Random integer values in the range specified
int p = ThreadLocalRandom.current().nextInt(5,15);
int q = ThreadLocalRandom.current().nextInt(30,35);

System.out.println("Randomly Generated Integer Values in the RANGE:");  
System.out.println(p);   
System.out.println(q); 

// Generate Random double values  
    double c = ThreadLocalRandom.current().nextDouble();   
    double d = ThreadLocalRandom.current().nextDouble();

// Print random doubles   
    System.out.println("\nRandomly Generated Double Values:");  
    System.out.println(c);   
    System.out.println(d);   

// Generate random boolean values  
    boolean e = ThreadLocalRandom.current().nextBoolean();   
    boolean f = ThreadLocalRandom.current().nextBoolean();   

// Print random Booleans   
    System.out.println("\nRandomly Generated Boolean Values:");  
    System.out.println(e);   
    System.out.println(f);   

    }   
}

Take a look at the Output of this Code Block

ints() method in Java 8

In Java 8, a new method ints() has been added to the Random class " java.util.Random"

ints() method is same as calling the nextInt() method. It returns an unlimited stream of pseudorandom int values. It can be used in different ways:

  • ints(long streamSize) - The method parses a parameter streamSize of type long. It specifies the number of values to be generated. It throws IllegalArgumentException if the stream size is less than zero.

  • ints(long streamSize, int randomNumberOrigin, int randomNumberBound) - It returns a stream of pseudorandom int values with the specified origin and bound. It throws IllegalArgumentException if: stramSize < 0 or origin > = bound.

import java.util.Random;

public class RandomNumberExample5 {

    public static void main(String[] args) {

        randomInts(4);
        randomIntsInBounds(12, 5, 15);
    }

//method that generates a stream of integers having size 4  
    public static void randomInts(int value) {
        Random randomNumbers = new Random();

        System.out.println("Randomly Genereated Values: ");
        randomNumbers.ints(value).forEach(System.out::println);
    }

// method that generates a stream of integers having size 12 between range of 5 to 15 

    public static void randomIntsInBounds(int value, int lower, int upper) {
        Random randomNumbers = new Random();

        System.out.println("Randomly Genereated Values: ");
        randomNumbers.ints(value, lower, upper).forEach(System.out::println);
    }
}

Take a look at the Output of this Code Block

I am always working on some cool Projects. So feel free to follow me on these platforms:

©️ Hamit Sehjal 2022