Java Random nextInt() Method
Example
Roll a dice: get a random number from 1 to 6, and check that it is in that range:
import java.util.Random;
public class Main {
public static void main(String[] args) {
Random rand = new Random();
int dice = rand.nextInt(6) + 1;
System.out.println("Is the number between 1 and 6? " + (dice >= 1 && dice <= 6));
}
}
Definition and Usage
The nextInt() method returns a random int value.
Without a parameter, the number can be any int, positive or negative. With a parameter (the bound), the number is at least 0 and less than the bound. For example, nextInt(6) returns 0, 1, 2, 3, 4 or 5, so nextInt(6) + 1 gives a dice roll from 1 to 6.
Tip: To get a random number from min to max (both included), use rand.nextInt(max - min + 1) + min.
Syntax
One of the following:
public int nextInt()
public int nextInt(int bound)
Parameter Values
| Parameter | Description |
|---|---|
| bound | Optional. The upper limit. The random number is less than this value. It must be greater than 0. |
Technical Details
| Returns: | A random int value. With a bound, the value is from 0 up to bound - 1. |
|---|---|
| Throws: | IllegalArgumentException - if bound is 0 or less. |
Related Pages
Java How To Generate Random Numbers
❮ Random Methods