Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags


How to use RandomUtils to generate random integer values in Java


nextInt is a static method that can be used to generate random int values. There are two variations of the method:

  • One generates random integer values within zero to Integer.MAX_VALUE.
  • The other takes the range as parameters and generates random integer values within the specified range.


Example 1

  • lower bound - 0
  • upper bound - Integer.MAX_VALUE

The method that doesn’t accept any parameters is used here to generate a random integer value.

Example 2

  • lower bound - 32
  • upper bound - 100

The parameterized method is used here to generate a random integer value. The method accepts the lower and upper bounds as parameters.

How to import RandomUtils

RandomUtils is defined in the Apache Commons Lang package. Apache Commons Lang can be added to the Maven project by adding the following dependency to the pom.xml file.


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;

Variant 1


public static int nextInt()


The method takes no parameters.

Return value

The method returns a random int value within zero to Integer.MAX_VALUE.

Variant 2


public static int nextInt(int startInclusive, int 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.

Return value

nextInt returns a random integer value within the given range.

if startInclusive is greater than endExclusive or if startInclusive is negative than function throws IllegalArgumentException.


import org.apache.commons.lang3.RandomUtils;

public class Main {

    public static void main(String[] args) {
        int lowerBound = 32;
        int upperBound = 100;
        System.out.printf("Random integer generated between [%s, %s) is %s", lowerBound, upperBound, RandomUtils.nextInt(lowerBound, upperBound));
        System.out.printf("\nRandom integer generated between [0, Integer.MAX_VALUE) is %s", RandomUtils.nextInt());

Expected output

Random integer generated between [32, 100) is 33
Random integer generated between [0, Integer.MAX_VALUE) is 1703546462

When you run the code, your output can be different because a random number is generated.



View all Courses

Keep Exploring