Java Random nextInt

In this tutorial, we will see Java Random nextInt method.It is used to generate random integer.
There are two overloaded versions for Random nextInt method.

nextInt()

Syntax

Here random is object of the java.util.Random class.

Return

returns random integer.

Example

Let’s see a very simple example:

Output:

Random Integer: 1326186546
Random Integer: 203489674
Random Integer: -472910065

nextInt(int bound)

Syntax

Here random is object of the java.util.Random class and bound is integer upto which you want to generate random integer.
Random’s nextInt method will generate integer from 0(inclusive) to bound(exclusive)
If bound is negative then it will throw IllegalArgumentException

Return

returns random integer in range of 0 to bound(exclusive)

Example

Let’s see a very simple example:

As bound is exclusive, hence we have use random.nextInt(101) to generate integer from 0 to 100.
Output:

Generating 10 random integer from range of 0 to 100
72
100
98
69
62
90
88
16
16
61

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *