Generating random numbers in Java is a common requirement while working on Java application. In this article, we will look at how to generate random numbers in Java.
How to Generate Random Numbers in Java
Normally, we came up with 2 types of requirements to generate a random number or generate a random number within a range. Java supports random number generation through ThreadLocalRandom
, java.lang.Math
and java.util.Random
classes. Let’s see what are the different options and how to generate random numbers in Java.
1. Generate Random Number Using ThreadLocalRandom
If you are using Java 1.7 or later, ThreadLocalRandom
should be your standard way to generate the random numbers in Java. There can be 2 variations while generating a random numbers in Java or any other language.
- Generate random number with no range.
- Generate random number within given range.
package com.javadevjournal.date;
import java.util.concurrent.ThreadLocalRandom;
public class RandomNumberGeneration {
public static void main(String[] args) {
int lowerBound = 4;
int upperBound = 20;
int random_int = ThreadLocalRandom.current().nextInt(); //returns pseudorandom value
System.out.println(random_int); //output will be different on different machine (2063277431 while running example);
/*generate random int within given range between 0 upper given bound.
* The upper bound is non exclusive i'e it will not be counted while generating the
* random number.
* */
int random_int_with_upper_bound = ThreadLocalRandom.current().nextInt(upperBound);
System.out.println(random_int_with_upper_bound); // 6 while we were running the code.
/**
* Generate random number with a given range of lower and upper bound.
*/
int random_int_range = ThreadLocalRandom.current().nextInt(lowerBound, upperBound + 1);
System.out.println(random_int_range); // 18 while we were running the code.
}
}
Keep in mind the following important point while using the ThreadLocalRandom
.
- If you don’t provide lower-bound, it will take lower bound as 0.
- upper bound is non exclusive, you need to be careful if you want to add upper range in the random number generation (add 1 to the upper range to include it).
- We don’t need explicit initialize with the
ThreadLocalRandom
class. - If the bound is
<=0
, it will throwIllegalArgumentException
. - If lower-bound is greater than or equal to upper bound, class will throw
IllegalArgumentException
.
int lowerBound = 4;
int upperBound = 3;
/**
* These will throw IllegalArgumentException.
*/
ThreadLocalRandom.current().nextInt(lowerBound, upperBound);
ThreadLocalRandom.current().nextInt(0);
The nextDouble()
and nextFloat()
method allows generating the float and double values.It works similar to the above example and we can pass the lower and upper bound while generating the random double or float numbers.
ThreadLocalRandom.current().nextDouble();
ThreadLocalRandom.current().nextDouble(1.0, 34.0);
ThreadLocalRandom.current().nextFloat();
2. Using Random Class
If you are not using Java 1.7 or higher, we can use the java.util.Random
class to generate random numbers in Java.Here are some details for this class:
nextInt(upperBound)
– Generate random int between0
and upperbound-1
;nextFloat()
– Generate float between0.0
to1.0
.nextDouble()
– Generate double between0.0
to1.0
.
package com.javadevjournal.date;
import java.util.Random;
public class RandomNumberGeneration {
public static void main(String[] args) {
int min = 1;
int max = 67;
Random random = new Random();
//Get random int between [0-66]
int randomInt = random.nextInt(max);
/*
If we want to include 67 in the range, add 1 to the upper bound
i.e max+1
generate random int between [0- 67]
*/
int upperBoundInt = random.nextInt(max + 1);
//another variation
int randomNum = random.nextInt((max - min) + 1) + min;
//Double random number
double randomDouble = random.nextDouble();
float randomFloat = random.nextFloat();
}
}
3. Using Math.random
We can use Math.random in case we only need integer or float random values.Here is a sample code from Math.random
class:
double random = Math.random();
This will return a positive double value that is greater than or equal to 0.0
and less than 1.0
.In many use-cases, we may like to generate a random number within given range.One of the option to do that is using the following expression
<pre>Math.random() * ((max - min) + 1)) +min
Math.random()
generates a double value in the range[0,1)
.- To get a specific range of values, We should multiple by the magnitude of the range of values we want covered (
* ( Max - Min )
). - Shift this range up to the range that you are targeting. You do this by adding the min value (last part of expression
+min
)
public class RandomNumberGeneration {
public static void main(String[] args) {
double min = 1;
double max = 67;
/*
Generate random number with in given range
*/
double random = (int)(Math.random() * ((max - min) + 1));
System.out.println(random);
}
}
4. Math.random() versus Random.nextInt(int)
If you are only interested in getting the int as the random number, you should choose the Random.nextInt(n)
as this option is more efficient and less biased.Here are some of the advantages of using Random.nextInt
over Math.random()
Math.random()
usesRandom.nextDouble()
internally. It’s better to use the original one than routing through it.Random.nextInt(n)
is repeatable. We can create 2 different Random objects by passing same seed.Math.random()
also requires about twice the processing and is subject to synchronization.
5. Generate Random numbers using Java 8
Though most of the cases can be easily fulfilled using ThreadLocalRandom
, however , if you are more interested in how to generate random numbers in Java 8 , here are few options to accomplish it using Java 8
import java.util.Random;
import java.util.SplittableRandom;
import java.util.stream.IntStream;
public class RandomNumberGeneration {
public static void main(String[] args) {
int min = 1;
int max = 67;
int size=50;
/*
return int between the specified
* min range (inclusive) and the specified upper bound (exclusive).
*/
int randomInt= new SplittableRandom().nextInt(min, max);
//TO return stream of random values
IntStream stream = new SplittableRandom().ints(size, min, max);
// to generate int[]
int[] randomArray= new SplittableRandom().ints(size, min, max).toArray();
int[] randomArray1= new Random().ints(size, min,max).toArray();
}
}
Summary
In this article, we saw how to generate random numbers in Java. We saw how to use the ThreadLocalRandom
to generate the random numbers if you are using Java 1.7 or higher version or how to use other options to generate random numbers if still using Java 1.6 or lower version. There are few external libraries which can be used to generate random numbers in Java, however we should use the built in Java methods as they can work for all types of use cases.Here is a decision chart for you which can help to decide among the different options.