How to generate random long values in Java
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:
- One takes the range as parameters and generates random long values within the specified range.
- The other generates random long values within zero to
Long.MAX_VALUE.
How to import 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-langpackage.
You can import the RandomUtils class as follows.
import org.apache.commons.lang3.RandomUtils;
Method 1
Syntax
public static long nextLong(final long startInclusive, final long endExclusive)
Parameters
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.
Return value
nextLong returns a random long value within the given range.
Method 2
Syntax
public static long nextLong()
Parameters
The method takes no parameters.
Return value
The method returns a random long value within zero to Long.MAX_VALUE.
Code
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());}}
Example 1
- Lower bound: 1000
- Upper bound: 234543
The parameterized method is used here to generate a random long value. The method accepts the lower and upper bounds as parameters.
Example 2
- Lower bound: 0
- Upper bound:
Long.MAX_VALUE
The method that doesn’t accept any parameters is used here to generate a random long value.
Expected output
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.