What is RandomUtils.nextInt in Java?

nextInt is a static method of the RandomUtils class that returns a random integer value.

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.

<dependency>
   <groupId>org.apache.commons</groupId>
   <artifactId>commons-lang3</artifactId>
   <version>3.12.0</version>
</dependency>

For other versions of the commons-lang package, refer to the Maven Repository.

Syntax

public static int nextInt()

Parameters

The nextInt method doesn’t take any parameters.

Return value

This method returns a random integer value.

The returned random integer value will be within 0 to Integer.MAX_VALUE.

Code

In the code below, we use the nextInt method as follows:

import org.apache.commons.lang3.RandomUtils;
class NextIntExample {
public static void main( String args[] ) {
System.out.println("RandomUtils.nextInt() => " + RandomUtils.nextInt()); // random int value
System.out.println("RandomUtils.nextInt() => " + RandomUtils.nextInt()); // random int value
}
}

Explanation

In the code above:

  • Line 1: We import the RandomUtils class.
import org.apache.commons.lang3.RandomUtils;
  • Lines 5 and 6: We use the nextInt method to get the random integer value.

Expected output

RandomUtils.nextInt() => 12
RandomUtils.nextInt() => 189

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

Free Resources