How to generate a random number in Java

In the Java programming language, various applications find the need to generate random numbers. Therefore, Java provides various ways to generate random numbers in a specific range for the integer,long,double, float, and Boolean types.

Various applications use the feature of random numbers. For example, the one-time password (OTP) is used to authenticate the user. Also,a dice is one of the examples of random numbers which gives a random value between 1 and 6, whenever we throw it.

In this section, we will understand a random number and the different ways to generate a random number in Java.

Random number

Random numbersoccur in a sequence and select a number using some mathematical algorithm. These numbers fulfill two conditions:

  1. The valuesgenerated are uniformly distributed over a defined interval or set.
  2. The future value cannot be predetermined merely using present and past values.

How to generate random numbers in Java?

In Java, the random numbers can be generated using some built-in classes and methods. Here, we will learn about five different ways, using which we can generate random numbers.

  • Using java.util.Random class
  • Using the Math.random() method
  • Using the ThreadLocalRandom class
  • Using Java 8 ints() method
  • Using SplittableRandom class

Note: The last two ways mentioned above can only be used in Java version 8 and above.

Using java.util.Random class

Generating random numbers using the Random class of java.util package was the most popular way before Java 1.7. Astream of pseudorandom numbers is generated using the Random class.

We can generate random numbers of different types like int, float, double, boolean, and long using different methods as:

Data typeMethod name
IntnextInt(int bound) nextInt()
FloatnextFloat()
doublenextDouble()
booleannextBoolean()
LongnextLong()

All these methods return the next pseudorandom and homogenously distributed value from the sequence.

Note:

  • The methods nextDouble() and nextFloat() generate random value between the range 0.0 and 1.0.
  • The nextInt(int bound) method accepts a parameter to place the upper bound on the range of random numbers to be generated. This method generates numbers in the range of 0 to -1. Also, the bound parameter must be positive (bound > 0), or it will generate java.lang.IllegalArgumentException.

For example, the method nextInt(10) generates random numbers ranging from 0 to 9, both inclusive.

  • The nextInt() method returns an integer value with approximately equal probability. Thus, we may also get negative numbers.

We have to perform following steps to generate random numbers using java.util.Random class:

  1. Import the class java.util.Random
  2. Create an instance of Random class

Example:

Random r_obj = new Random();

  • Invoke the required method of the r_obj object

Example:

int randomInt = r_obj.nextInt();

And if we use nextInt(int bound), random numbers are generated within a specific range

Example:

int randomIntWithinRange = r_obj.nextInt(8);

Let’s consider the following example that uses the Random class to generate random numbers:

TestRandomClass.java

Output:

Using the Math.random() method

The random() method of the Math class also allows us to generate the random numbers. As it is a static method, it can be invoked directly. The random() method returns a positive random number of typeDouble, which isgreater than or equal to 0.0 and less than 1.0.

To use this method, we need to import java.lang.Math class.

Syntax:

Itdoes not accept any parameter and generates a pseudorandom double value.

Let’s consider the following example to generate random numbers using the Math.random() method.

TestRandomMethod.java

Output:

Note: Every time we execute the program, it will generate different output.

Now, to generate a random number of type double within a specified range of values, we can use the formula:

double randomDoubleWithinRange = Math.random() * (max-min + 1) + min;

where the min value is inclusive, and the max value is exclusive in the range.

And to get the numbers of int type within a specified range, we have to use the formula as:

int randomIntWithinRange = (int) (Math.random() * (max-min + 1)+ min);

Consider the following example to generate the random numbers of type double and int between a range 25 to 100.

TestRandomMethod2.java

Output:

Using the ThreadLocalRandom class

One of the ways to generate random numbers is using the ThreadLocalRandom class of the java.util.concurrent package. It was introduced in Java version 1.7 and used to generate random numbers of types int, double,float, long andboolean.

There are few major differences between ThreadLocalRandom class and the Random class:

  • There is no need to create a new object of ThreadLocalRandom explicitly. This feature allows us to efficiently write the code without creating unnecessary objects and wasting the time of the Java garbage collector.
  • The initialization is done using the internally generated seed. So the seed cannot be set. Thus, if there is a need to set the seed, it is not preferred to use this way to generate random numbers.
  • Random class is unfeasible in multi-threaded environments.

In order to generate random numbers using ThreadLocalRandom class, we have to perform the following steps:

  1. Import java.util.concurrent.ThreadLocalRandom
  2. Invoke a method to generate random numbers of required data types. These methods override the corresponding methods of the Random class and return the value with respect to that method.
  3. nextInt()
  4. nextFloat()
  5. nextBoolean()
  6. nextDouble()
  7. nextLong()

Now, the following methods accept a parameter which is an upper bound value. It must be positive,or it throws IllegalArgumentException. It generates a stream of random numbers from 0 (inclusive) to the bound value.

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

Few methods accept two parameters,origin and bound. Here origin specifies the start value, and bound specifies the end value of the random numbers stream. These methods return the random numbers between the start value (inclusive) and end value (exclusive). If the origin >= bound, it throws IllegalArgumentException.

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

Let’s consider the below example to generate random numbers using the ThreadLocalRandom class:

TestThreadLocalRandomClass.java

Output:

Consider the below example, which generates random integer numbers within the specified range of values. Here, we use the methodsnextInt(int bound) and nextInt(int origin, int bound). We can also generate the random numbers of type double and long using the corresponding methods explained above.

TestThreadLocalRandomClass2.java

Output:

Generating random numbers in Java 8

  1. Using ints() method

Java 8 has introduced a new method in the java.util.Random class to generate random numbers is called the ints() method. It return a java.util.stream.IntStream. Similar to the nextInt() method, it generates the pseudorandom int values.

  1. ints():

The ints() method without any parameter returns an unlimited stream of int values.

Syntax:

  • ints(long streamSize):

The ints(long streamSize) method returns a limited stream of random int values. It accepts a parameter streamSize of type long, which is used to limit the size of the stream. The stream size must be greater than 0, or it will throw IllegalArgumentException.

Syntax:

  • ints(long streamSize, int, int minRandom, maxRandom):

where,

  • streamSize is the number of random values to be generated.
  • minRandom is the start of random stream.
  • maxRandom is the bound of random stream.

This method generates a stream of int values within a specified range of start and end values. Even this method throws IllegalArgumentException if streamSize< 0 and minRandom>= maxRandom.

Syntax:

  • ints(int minRandom, int maxRandom):

Similar to the above method, this method returns an unlimited stream of random int values within a specified range. If the minRandom>= maxRandom, it throws IllegalArgumentException.

Syntax:

Note: We can also generate the stream of random numbers of type long and double using the methods longs() and doubles().

Let’s consider the following example to generate random numbers using the ints() method. Here, we use ints(streamSize) and ints(streamSize, minRandom, maxRandom) types of methods. The other two types generate unlimited random numbers giving the infinite output.

RandomIntsMethod.java

Output:

  • Using SplittableRandom class

Along with the ints() method, Java 8 has also introduced the SplittableRandom class. It is the fastest random number generator used primarily on parallel computations.

There are various methods of SplittableRandom class to generate random numbers of type int, double, long, and Boolean. Some of the majorly used methods are:

Data typeMethod Name
intints() nextInt()
doubledoubles() nextDouble()
longlongs() nextLong()
booleannextBoolean()

Note: While using the SplittableRandom class, we should remember that its instances are not thread-safe.

For example, lets generate random numbers using the nextInt() and ints() methods.

In the nextInt() method, we can specify the range of numbers with the help of parameters minRandom and maxRandom, respectively as

Here, if maxRandom>= minRandom, it will throw IllegalArgumentException. The parameter may be positive or negative.

Now to generate a stream of pseudorandom integer numbers,we can usethe ints() method. The stream may be unlimited or limited based on the parameters.

For generating limited stream, we use

IntStreamRandomIntWithinRange = splittableRandomObj.ints(streamSize, min, max);

TestSplittableRandom.java

Output:

In this way, we have learned how to generate random numbers in Java using different classes and methods.

Pin It on Pinterest

Share This