How to Generate Random Number Program in Java?

In Java programming, generating random numbers is a common requirement when developing applications. Random numbers play a crucial role in various functionalities, such as user verification through one-time passwords (OTPs). A classic example illustrating the use of random numbers is a dice, where rolling produces a random outcome between 1 and 6.

Random Number in Java

Random numbers are generated using mathematical algorithms that select numbers from a large set of values. The generation process adheres to two important conditions:

  • The generated values are uniformly distributed over a definite interval.
  • It is impossible to guess the future value based on current and past values.

Generating Random Numbers in Java

In Java, there are multiple ways to generate random numbers using different methods and classes:

  • Using the random() Method: The random() method is part of the Math class in Java. It returns a random double value between 0.0 and 1.0. Developers can manipulate the result to generate random numbers within a specific range.
  • Using the Random Class: The Random class in Java provides a more flexible way to generate random numbers. By creating an instance of the Random class, developers can use its various methods to generate random numbers of different types, including integers, doubles, and booleans.
  • Using the ThreadLocalRandom Class: The ThreadLocalRandom class is an alternative to the Random class, introduced in Java 7. It provides a thread-local random number generator that is faster and offers better performance in multi-threaded environments.
  • Using the ints() Method (in Java 8): Starting from Java 8, the java.util.random class provides an ints() method that generates a stream of random integers. This method allows developers to generate a sequence of random integers with specific parameters, such as range and size.

Using the Math.random() Method

The Math class in Java provides various methods for performing mathematical operations. One of these methods is random(), which is a static method. It can be directly invoked without the need for creating an instance of the Math class. The random() method generates random numbers of type double within the range of 0.0 (inclusive) to 1.0 (exclusive). To use the random() method in Java, the java.lang.Math class needs to be imported beforehand.

Syntax:

public static double random()

The random() method of the Math class in Java does not require any parameters. When invoked, it generates a pseudorandom double value that falls within the range of 0.0 (inclusive) to 1.0 (exclusive).

Let’s create a program that generates random numbers using the random() method.

RandomNumberExample1.java

import java.lang.Math;   
public class RandomNumberExample  
{   
public static void main(String args[])   
{   
// Generating random numbers  
System.out.println("1st Random Number: " + Math.random());   
System.out.println("2nd Random Number: " + Math.random());  
System.out.println("3rd Random Number: " + Math.random());   
System.out.println("4th Random Number: " + Math.random());   
}   
}

Output:

1st Random Number: 0.17434160924512265
2nd Random Number: 0.4297410090709448
3rd Random Number: 0.4828656381344487
4th Random Number: 0.13267917059488898

Note: Every time we get a different output when we execute the above program.

The following formula is used to generate random number between a specified range.

Math.random() * (max - min + 1) + min

Let’s create a program for generating random numbers between 200 to 400.

RandomNumberExample2.java

public class RandomNumberExample2  
{  
public static void main( String args[] )   
{  
int min = 200;  
int max = 400;  
//Generate random double value from 200 to 400   
System.out.println("Random value of type double between "+min+" to "+max+ ":");  
double a = Math.random()*(max-min+1)+min;   
System.out.println(a);  
//Generate random int value from 200 to 400   
System.out.println("Random value of type int between "+min+" to "+max+ ":");  
int b = (int)(Math.random()*(max-min+1)+min);  
System.out.println(b);  
}  
}

Output 1:

Random value of type double between 200 to 400:
233.88329802655377
Random value of type int between 200 to 400:
329

Output 2:

Random value of type double between 200 to 400:
254.8419979875385
Random value of type int between 200 to 400:
284

Generate Random Number using the Random Class

In Java, another approach to generate random numbers is by utilizing the Random class from Java.util package. This class enables the generation of pseudorandom numbers across various data types, including integers, floats, doubles, Booleans, and longs. To generate random numbers using the Random class, the following steps can be followed:

  • First, import the class java.lang.Random.
  • Create an object of the Random class.
  • Invoke any of the following methods:
  • nextInt(int bound)
  • nextInt()
  • nextFloat()
  • nextDouble()
  • nextLong()
  • nextBoolean()

The methods mentioned above, such as nextDouble() and nextFloat(), return the next pseudorandom value from the sequence generated by the random number generator. These methods provide homogeneously distributed random values between 0.0 and 1.0.

Additionally, the nextInt(int bound) method is available, which accepts a positive parameter called “bound” (upper bound). It generates a random integer within the range of 0 to bound-1. By specifying the upper bound, you can control the range of random numbers generated using this method.

Let’s write a program to generate Random numbers using the Random class.

RandomNumberExample3.java

import java.util.Random;   
public class RandomNumberExample2  
{   
public static void main(String args[])   
{   
// creating an object of Random class   
Random random = new Random();   
// Generates random integers 0 to 49  
int x = random.nextInt(50);   
// Generates random integers 0 to 999  
int y = random.nextInt(1000);   
// Prints random integer values  
System.out.println("Randomly Generated Integers Values");  
System.out.println(x);   
System.out.println(y);   
// Generates Random doubles values  
double a = random.nextDouble();   
double b = random.nextDouble();   
// Prints random double values  
System.out.println("Randomly Generated Double Values");  
System.out.println(a);   
System.out.println(b);    
// Generates Random float values  
float f=random.nextFloat();  
float i=random.nextFloat();  
// Prints random float values  
System.out.println("Randomly Generated Float Values");  
System.out.println(f);   
System.out.println(i);   
// Generates Random Long values  
long p = random.nextLong();   
long q = random.nextLong();   
// Prints random long values  
System.out.println("Randomly Generated Long Values");  
System.out.println(p);   
System.out.println(q);    
// Generates Random boolean values  
boolean m=random.nextBoolean();  
boolean n=random.nextBoolean();  
// Prints random boolean values  
System.out.println("Randomly Generated Boolean Values");  
System.out.println(m);   
System.out.println(n);   
}   
}

Output:

Randomly Generated Integers Values
23
767
Randomly Generated Double Values
0.37823814494212016
0.998058172671956
Randomly Generated Float Values
0.87804186
0.93880254
Randomly Generated Long Values
-4974823544291679198
3650240138416076693
Randomly Generated Boolean Values
false
true

Using the ThreadLocalRandom Class

The ThreadLocalRandom class is part of the java.util.concurrent package and provides a way to generate random numbers. It is initialized with a seed generated internally, similar to the random generator in the Math class. The seed cannot be modified. To use the ThreadLocalRandom class, follow the steps outlined below:

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

Where X is Int, Long, etc.

The ThreadLocalRandom class in Java allows us to generate random numbers of various data types, including integers, floats, doubles, Booleans, and longs. If you intend to use this class for generating random numbers, follow the steps below:

  • First, import the class by using java.util.concurrent.ThreadLocalRandom.
  • Invoke the corresponding method for which you want to generate numbers randomly.
  • nextInt()
  • nextDouble()
  • nextLong()
  • nextFloat()
  • nextBoolean()

Each of the mentioned methods in the ThreadLocalRandom class overrides the corresponding method in the Random class and returns the respective random value.

  • nextInt(int bound)
  • nextDouble(int bound)
  • nextLong(int bound)

The above-mentioned methods in the ThreadLocalRandom class accept a positive parameter bound, which specifies the upper limit. They generate a random value within the range from 0 (inclusive) to the specified bound (exclusive). If the bound is negative, an IllegalArgumentException is thrown.

  • nextInt(int origin, int bound)
  • nextDouble(int origin, int bound)
  • nextLong(int origin, int bound)

The mentioned methods in the ThreadLocalRandom class take two parameters: origin and bound. The origin parameter specifies the minimum value that can be returned, while the bound parameter specifies the upper limit (exclusive). These methods generate random values within the range starting from the specified origin (inclusive) up to the bound (exclusive). If the origin value is greater than or equal to the bound value, an IllegalArgumentException is thrown.

Let’s write a program for generating random numbers using the ThreadLocalRandom class.

RandomNumberExample4.java

import java.util.concurrent.ThreadLocalRandom;   
public class RandomNumberExample3  
{   
public static void main(String args[])   
{   
// Generate random integers between 0 to 999   
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 double values  
double c = ThreadLocalRandom.current().nextDouble();   
double d = ThreadLocalRandom.current().nextDouble();   
// Print random doubles   
System.out.println("Randomly 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("Randomly Generated Boolean Values:");  
System.out.println(e);   
System.out.println(f);   
}   
}

Output 1:

Randomly Generated Integer Values:
348534891
-1887936727
Randomly Generated Double Values:
0.15644440033119833
0.5242730752133399
Randomly Generated Boolean Values:
true
true

Output 2:

Randomly Generated Integer Values:
402755574
295398333
Randomly Generated Double Values:
0.4856461791062565
0.5148677091077654
Randomly Generated Boolean Values:
false
true

Random Number Generation in Java 8

Starting from Java 8, the Random class introduced a new method called ints(). To utilize this method, we need to import the java.util.Random package. The ints() method allows us to generate a stream of random integer values.

ints():

The generated pseudorandom integer values are identical to those produced by invoking the nextInt() method. It provides an infinite sequence of pseudorandom integer values.

ints(long streamSize):

This method accepts a long parameter called streamSize, which indicates the desired number of values to be generated. The generated pseudorandom integer values are equivalent to those obtained by invoking the nextInt() method. Furthermore, it returns a stream of int values that are randomly generated. If the stream size is negative, an IllegalArgumentException is thrown.

ints(long streamSize, int randomNumberOrigin, int randomNumberBound):

Parameters:

  • streamSize: Number of values to generate.
  • randomNumberOrigin: Origin of each random value
  • randomNumberBound: Bound of each random value

It returns a stream of pseudo-random int values with the specified origin and bound. It gives IllegalArgumentException if:

  • streamSize < 0
  • origin > = bound
ints(int randomNumberOrigin, int randomNumberBound):

Parameters:

  • randomNumberOrigin: Origin of each random value
  • randomNumberBound: Bound of each random value

The method returns an infinite stream of pseudorandom integer values within the specified range of origin and bound. However, if the origin is greater than or equal to the bound, it will throw an IllegalArgumentException.

Similarly, we can generate streams of long and double types by utilizing the longs() and doubles() methods, respectively.

Now, let’s proceed with developing a program that utilizes the ints() method from the Random class to generate a stream of integers.

RandomNumberExample5.java

import java.util.Random;   
public class RandomNumberExample4   
{   
public static void main(String[] args)   
{   
randomInts(5);  
randomInts(9, 50, 90);  
//getStreamOfRandomInts(30, 50);  
}   
//method that generates a stream of integers having size 5  
public static void randomInts(int num)   
{  
Random random = new Random();  
random.ints(num).forEach(System.out::println);  
}  
//method that generates a stream of 9 integers between 50 to 90  
public static void randomInts(int num, int origin, int bound)   
{  
Random random1 = new Random();  
random1.ints(num, origin, bound).forEach(System.out::println);  
}  
}

Output 1:

727900357
-1073118456
306279822
370327182
1366265119
65
75
75
88
76
75
56
86
85

Output 2:

-1338107947
-1698771421
594232770
-1224937976
-1625069815
56
69
67
87
64
52
72
75
76

Hope you understand How to generate a random number program in Java? Follow tutorials.freshersnow.com to learn more.