Random long
values can be generated using the nextLong
method of the RandomUtils
class.
nextLong
is a static method that generates random long
values. There are two variations of the method. They are as follows:
Long.MAX_VALUE
RandomUtils
?RandomUtils
is defined in the Apache Commons Lang package. You can add the Apache Commons Lang to the Maven project by adding the following dependency to the pom.xml
file.
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version>
</dependency>
Note: For other versions of the commons-lang package, refer to the Maven Repository.
You can import the RandomUtils
class as follows:
import org.apache.commons.lang3.RandomUtils;
public static long nextLong(final long startInclusive, final long endExclusive)
startInclusive
- the lower bound of the range or the smallest value that can be returnedendExclusive
- the upper bound of the range that is not includedThis will return a random long value within the given range.
public static long nextLong()
The method takes no parameters.
A random long value within the range of zero to Long.MAX_VALUE
.
import org.apache.commons.lang3.RandomUtils;public class Main {public static void main(String[] args) {long lowerBound = 100L;long upperBound = 120L;System.out.printf("Random Number generated between [%s, %s) is %s",lowerBound, upperBound, RandomUtils.nextLong(lowerBound, upperBound));System.out.printf("\nRandom Number generated between [0, Long.MAX_VALUE) is %s", RandomUtils.nextLong());}}
In line 8 of the code above, the parameterized method is used here to generate a random long value. The method accepts lower and upper bound as the parameters.
Long.MAX_VALUE
In line 9 of the code above, the method which doesn’t accept parameters is used to generate a random long value.
The output of the code above is as follows:
Random Number generated between [100, 120) is 112
Random Number generated between [0, Long.MAX_VALUE) is 2111934587352218129
When you run the code, your output can be different