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
1 2 3 |
random.nextInt() |
Here random is object of the java.util.Random class.
Return
returns random integer.
Example
Let’s see a very simple example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
package org.arpit.java2blog; import java.util.Random; public class RandomNextIntMain { public static void main(String[] args) { Random random=new Random(); System.out.println("Random Integer: "+random.nextInt()); System.out.println("Random Integer: "+random.nextInt()); System.out.println("Random Integer: "+random.nextInt()); } } |
Output:
Random Integer: 203489674
Random Integer: -472910065
nextInt(int bound)
Syntax
1 2 3 |
random.nextInt(bound) |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
package org.arpit.java2blog; import java.util.Random; public class RandomNextIntMain { public static void main(String[] args) { Random random=new Random(); System.out.println("Generating 10 random integer from range of 0 to 100:"); for (int i = 0; i < 10; i++) { System.out.println(random.nextInt(101)); } } } |
As bound is exclusive, hence we have use random.nextInt(101) to generate integer from 0 to 100.
Output:
72
100
98
69
62
90
88
16
16
61