We can generate random long
values with the nextLong
method of the RandomUtils
class.
nextLong
is a static method that can generate random long
values.
There are two variations of the method:
Long.MAX_VALUE
.RandomUtils
RandomUtils
is defined in the Apache Commons Lang
package, which we can add 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>
Refer to the Maven Repository for other versions of the
commons-lang
package.
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 returned.endExclusive
: The upper bound of the range that is not included.nextLong
returns a random long value within the given range.
public static long nextLong()
The method takes no parameters.
The method returns a random long value within zero to Long.MAX_VALUE
.
import org.apache.commons.lang3.RandomUtils;public class Main {public static void main(String[] args) {long lowerBound = 1000;long upperBound = 234543;System.out.printf("Random long generated between [%s, %s) is %s", lowerBound, upperBound, RandomUtils.nextLong(lowerBound, upperBound));System.out.printf("\nRandom long generated between [0, Integer.MAX_VALUE) is %s", RandomUtils.nextLong());}}
The parameterized method is used here to generate a random long value. The method accepts the lower and upper bounds as parameters.
Long.MAX_VALUE
The method that doesn’t accept any parameters is used here to generate a random long value.
Random long generated between [1000, 234543) is 2247
Random long generated between [0, Integer.MAX_VALUE) is 4851981442751655696
When you run the code, your output may be different because a random number is generated.