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
random.nextInt()
Here random is object of the java.util.Random class.
Return
returns random integer.
Example
Let’s see a very simple example:
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
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:
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; iAs 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
61The post Java Random nextInt appeared first on Java2Blog.