Java Utility Library

Java Random - nextInt() Method



The java.util.Random.nextInt() method returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive), drawn from this random number generator's sequence.

Syntax

public int nextInt(int bound)

Parameters

bound Specify the upper bound (exclusive). Must be positive.

Return Value

Returns the next pseudorandom, uniformly distributed int value between zero (inclusive) and bound (exclusive) from this random number generator's sequence.

Exception

Throws IllegalArgumentException, if bound is not positive.

Example:

In the example below, the java.util.Random.nextInt() method is used to get pseudorandom number, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive).

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating a random object
    Random rand = new Random();

    //printing uniformly distributed int random numbers
    //between 0 and 100(exclusive).
    for(int i = 0; i < 5; i++)
      System.out.println("Next Int Value: " + rand.nextInt(100)); 
  }
}

One of the possible outcome is given below:

Next Int Value: 74
Next Int Value: 40
Next Int Value: 70
Next Int Value: 31
Next Int Value: 12

❮ Java.util - Random