Javatpoint Logo
Javatpoint Logo

Java Random nextInt() Method

The nextInt() method of Random class returns the next pseudorandom, uniformly distributed int value from the random number generator's sequence.

Syntax

Parameters

NA

Return Value

The nextInt() method returns the next pseudorandom int value drawn from the random number generator's sequence.

Example 1

Test it Now

Output:

Random Integer value : -298063488
Random Integer value : 1400961289

Java Random nextInt() Method

The nextInt(int n) method of Random class returns a pseudorandom int value between zero (inclusive ) and the specified value(exclusive), drawn from the random number generator?s sequence.

Syntax

Parameters

n: It is the bound on the random number to be returned. It must be positive.

Return Value

The nextInt() method returns the next pseudorandom int value between zero and n drawn from the random number generator's sequence.

Throws

The nextInt() method throws IllegalArgumentException, if n is not positive.

Example 2

Test it Now

Output:

1. Random intvalue : 0 
2. Random intvalue : 1 
3. Random intvalue : 0 
4. Random intvalue : 3 
5. Random intvalue : 1 
6. Random intvalue : 0 
7. Random intvalue : 0 

Example 3

Test it Now

Output:

Enter number of players.3
Enter name of 3 Players.
1 Sukla
2 Mukta
3 Amar
1. Sukla will have 0 bonus points.
2. Mukta will have 1 bonus points.
3. Amar will have 2 bonus points.

Example 4

Test it Now

Output:

Exception in thread "main" java.lang.IllegalArgumentException: bound must be positive
	atjava.util.Random.nextInt(Random.java:388)
	at com.javaTpoint.JavaRandomNextIntExample4.main(JavaRandomNextIntExample4.java:9)

Note: The bound value must be positive else it will give IllegalArgumentException.

Next TopicJava Random




Help Others, Please Share

facebook twitter pinterest