Javatpoint Logo
Javatpoint Logo

How to Generate Random Number in Java

In Java programming, we often required to generate random numbers while we develop applications. Many applications have the feature to generate numbers randomly, such as to verify the user many applications use the OTP. The best example of random numbers is dice. Because when we throw it, we get a random number between 1 to 6.

In this section, we will learn what is a random number and how to generate random numbers in Java.

Random Number

Random numbers are the numbers that use a large set of numbers and selects a number using the mathematical algorithm. It satisfies the following two conditions:

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

Generating Random Number in Java

In Java, there is three-way to generate random numbers using the method and classes.

  • Using the random() Method
  • Using the Random Class
  • Using the ThreadLocalRandom Class
  • Using the ints() Method (in Java 8)

Using the Math.random() Method

The Java Math class has many methods for different mathematical operations. One of them is the random() method. It is a static method of the Math class. We can invoke it directly. It generates only double type random number greater than or equal to 0.0 and less than 1.0. Before using the random() method, we must import the java.lang.Math class.

Syntax:

It does not accept any parameter. It returns a pseudorandom double that is greater than or equal to 0.0 and less than 1.0.

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

RandomNumberExample1.java

Output:

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

Remember: Every time we get a different output when we execute the program. Your output may differ from the output shown above.

We can also use the following formula if we want to a generate random number between a specified range.

In the above formula, the min value is inclusive while the max value is exclusive.

Let's create a program that generates random numbers between 200 to 400.

RandomNumberExample2.java

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

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. If you are going to use this class to generate random numbers, follow the steps given below:

  • 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()

All the above methods return the next pseudorandom, homogeneously distributed value (corresponding method) from this random number generator's sequence. The nextDouble() and nextFloat() method generates random value between 0.0 and 1.0.

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.

Let's create a program that generates random numbers using the Random class.

RandomNumberExample3.java

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 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. We can use this class in the following way:

Where X is Int, Long, etc.

Note: It is impossible to share a ThreadLocalRandom with multiple threads accidentally.

We can generate a random number of any data type, such as integer, float, double, Boolean, long. If you are going to use this class to generate random numbers, follow the steps given 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()

All the above methods override the corresponding method of the Random class and return the corresponding value.

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

The above methods parse a parameter bound (upper) that must be positive. It returns corresponding randomly generated value between 0 (inclusive) and the specified bound (exclusive). It throws IllegalArgumentExcetion if the bound is negative.

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

The above methods parse two parameters origin and bound. The origin specifies the least value returned and the bound specifies the upper bound. It returns corresponding randomly generated value between the specified origin (inclusive) and bound (exclusive). Also, throws IllegalArgumentExcetion if the origin is greater than or equal to bound.

Let's create a program that generates random numbers using the ThreadLocalRandom class.

RandomNumberExample4.java

Output 1:

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

Output 2:

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

Similarly, we can use other methods of ThreadLocalRandomclass.

Random Number Generation in Java 8

In Java 8, a new method ints() has been added to the Random class. We must import the java.util.Random before using the method.

ints():

The pseudorandom int values generated the same as calling the nextInt() method. It returns an unlimited stream of pseudorandom int values.

ints(long streamSize):

The method parses a parameter streamSize of type long. It specifies the number of values to be generated. The pseudorandom int values generated the same as calling the nextInt() method. It also returns a stream of randomly generated int values. It throws IllegalArgumentException if the stream size is less than zero.

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 pseudorandom int values with the specified origin and bound. It throws IllegalArgumentException if:

  • stramSize < 0
  • origin > = bound

Parameters:

  • randomNumberOrigin: Origin of each random value
  • randomNumberBound: Bound of each random value
  • It returns an unlimited stream of pseudorandom int values with the specified origin and bound. It throws IllegalArgumentException if the origin is greater than or equal to bound.

    Similarly, we can also generate the stream of long and double types by using the longs() and doubles() method, respectively.

    Let's create a program that generates a stream of integers using the ints() method of the Random class.

    RandomNumberExample5.java

    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
    

    Next TopicJava Tutorial





    Youtube For Videos Join Our Youtube Channel: Join Now

    Feedback


    Help Others, Please Share

    facebook twitter pinterest

    Learn Latest Tutorials


    Preparation


    Trending Technologies


    B.Tech / MCA