You are on page 1of 4

How to generate random number in Java

Random numbers are the numbers that use a large set of numbers and selects a number using the mathematical algorithm. It
satisfied 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.
In java there are three-way to generate random numbers using the method and classes.
 Using random() method
 Using Random class
 Using the ThreadLocalRandom class
 Using the ints() method (in java8)
Using the Math.random() method
It is static method of Math class. It generates only double type method number greater than or equal to 0.0 and less the 1.0.
Before using random() method we must import the java.lang.Math class.
Public static double random();
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 understand with the help of example -

package javapractice;
import java.lang.Math;
public class RandomNumber {
public static void main(String[] args) {
System.out.println("1st Random number : " + Math.random());
System.out.println("2nd Random number : " + Math.random());
System.out.println("3rd Random number : " + Math.random());
}
}
In this example – every time we get a different output when we execute this program.

Example – 2 (This program to show how to generate random number between a specified range.)
package javapractice;
public class RandomNumber_2 {
public static void main(String[] args) {
int min = 200;
int max = 400;
System.out.println("Random value of type double between : " +min + " and " + max);
double a = Math.random()*(max - min + 1)+min;
System.out.println(a);
System.out.println("Random value of type int between : " +min +" and " +max);
int value = (int)(Math.random()*(max - min +1)+min);
System.out.println(value);
}
}
Using Random class
In java Random class is available in java.util package. It generates a stream of pseudorandom numbers. We can generate
random number of any type, such as integer, float, double, boolean, long. If you want to use this class for generating random
number then following steps are followe -
 First import the class java.lang.Random
 Create an object of the Random class
 Invoke any of the following methods :
o NextInt(int bound)
o NextInt()
o NextFloat()
o NextDouble()
o NextLong()
o NextBoolean()
NextInt(int bound) --> this method accpts a parameter bound(upper) that must be positive. It generated a random number in
the range 0 to bound-1.
NextFload() and nextDouble() method generates random value between 0.0 to 1.0.
Let’s understand with the help of example -
package javapractice;
import java.util.Random;
public class RandomNumber_3 {
public static void main(String[] args) {
Random random = new Random();
int x = random.nextInt(50); // it generates number between 0 to 49
int y = random.nextInt(1000); // it generates number between 0 to 999.
System.out.println("Randomly generated integer value ==> ");
System.out.println(x);
System.out.println(y);
double a = random.nextDouble();
double b = random.nextDouble();
System.out.println("Randomly generated double value ==> ");
System.out.println(a);
System.out.println(b);

float f = random.nextFloat();
float i = random.nextFloat();
System.out.println("Randomly generated float value ==> ");
System.out.println(f);
System.out.println(i);

long p = random.nextLong();
long q = random.nextLong();
System.out.println("Randomly generated long value ==> ");
System.out.println(p);
System.out.println(q);

boolean m = random.nextBoolean();
boolean n = random.nextBoolean();
System.out.println("Randomly generated boolean value ==> ");
System.out.println(m);
System.out.println(n);
}
}
Using the ThreadLocalRandom Class
This class is defined in java.util.concurrent package. It is initialized as the random generator of the Math class. We can use this
class in the following way :-
ThreadLocalRandom.current().nextX();
Here, x is Int, long, etc.
NOTE – it is impossible to share a ThreadLocalRandom with multiple threads accidently.
With the help of this class we can generate a random number of any data type, such as integer, float, doble, Boolean, long. If
we want to use this class to generate random number then we need to follow following steps:
 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)
Above methods parse a parameter bound (upper) that must be positive. It returns corresponding randomly generated value
between 0 (inclusive) and specified bound (exclusive). It throws IllegalArgumentException 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 returns and the bound value
specifies the upper bound. It return corresponding randomly generated value between the specified origin (inclusive) and
bound (exclusive). These method also throws IllegalArgumentException if the origin is greater than or equal to bound.

Let’s understand with the help of example –


package javapractice;
import java.util.concurrent.ThreadLocalRandom;
public class RandomNumber_4 {
public static void main(String[] args) {
int a = ThreadLocalRandom.current().nextInt();
int b = ThreadLocalRandom.current().nextInt();
System.out.println("Randomly generated Integer values : ");
System.out.println(a);
System.out.println(b);

double c = ThreadLocalRandom.current().nextDouble();
double d = ThreadLocalRandom.current().nextDouble();
System.out.println("Randomly generated Double values : ");
System.out.println(c);
System.out.println(d);

boolean e= ThreadLocalRandom.current().nextBoolean();
boolean f = ThreadLocalRandom.current().nextBoolean();
System.out.println("Randomly generated Boolean values : ");
System.out.println(e);
System.out.println(f);
}

Random number Generation in Java 8


In java 8 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): this method take an argument of long type. It specifies the numbers of value 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) :


here,
streamSize  number of values to generate
randomNumberOrigin  origin value of each random value
randomNumberBound  Bound of each random value
It returns a stream of preudorandom int values with the specified origin and bound. It throws
IllegalArgumentException if:
 streamSieze < 0
 origin >= bound

ints (int randomNumberOrigin, int randomNumberBound):


here,
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 longs() and doubles()
method respectively.

Lets’s understand with the help of example –


package javapractice;
import java.util.Random;
public class RandomNumber_5 {
public static void main(String[] args) {
randomInt(5);
randomInts(9, 50, 90);
}

// method that generates a stream of integers having size 5


public static void randomInt(int num) {
Random random = new Random();
random.ints(num).forEach(System.out::println);
}

// method that generates a streams of 9 integer between 50 to 90


public static void randomInts(int num, int origin, int bound) {
Random random = new Random();
random.ints(num, origin, bound).forEach(System.out::println);
}

You might also like