Java Random.next() – Examples
In this tutorial, we will learn about the Java Random.next() method, and learn how to use this method to get a pseudorandom number, with the help of examples.
next(int bits)
Random.next() returns the next pseudorandom number from this Random Generator’s sequence.
Syntax
The syntax of next() method is
Random.next(int bits)
where
Parameter | Description |
---|---|
bits | The number of bits that will be considered for random number. |
Returns
The method returns protected integer.
Example 1 – next(bits)
Random.next() is a protected method of Random class. So, to use this class, we may have to create a class, say Example
with Random
as its parent class. Since, Example
is a child class of Random
, Example
can access protected class of Random.
Java Program
import java.util.Random;
public class Example extends Random{
public static void main(String[] args) {
Example random = new Example();
System.out.println(" Next Random Value : " + random.next(9));
System.out.println(" Next Random Value : " + random.next(15));
System.out.println(" Next Random Value : " + random.next(32));
System.out.println(" Next Random Value : " + random.next(4));
}
}
Output
Next Random Value : 174
Next Random Value : 10188
Next Random Value : -776918100
Next Random Value : 9
Output may vary, since the numbers are generated randomly.
Example 2 – next(bits) – bits = 1
In this example, we will give next() an argument of 1
. So, only one bit is used to generate the resulting random number.
We will call next(1) in a loop, so that, we can observe what next(1) returns for multiple runs.
Java Program
import java.util.Random;
public class Example extends Random{
public static void main(String[] args) {
Example random = new Example();
for(int i=0; i < 25; i++)
System.out.println(random.next(1));
}
}
Output
1
0
0
0
1
0
0
0
1
1
0
1
0
0
0
1
0
0
1
1
0
0
0
0
1
With one bit, we could only get either 0 or 1.
Output may vary, since the numbers are generated randomly.
Example 3 – next(bits) – bits = 3
In this example, we will give next() an argument of 3
. So, only three bits are used to generate the resulting random number. So, the next() should return a value in between 0 and 7, including these.
Java Program
import java.util.Random;
public class Example extends Random{
public static void main(String[] args) {
Example random = new Example();
for(int i=0; i < 25; i++)
System.out.println(random.next(3));
}
}
Output
2
0
4
3
2
0
1
7
5
5
2
7
4
6
0
1
6
4
1
3
3
0
6
4
0
Output may vary, since the numbers are generated randomly.
Conclusion
In this Java Tutorial, we have learnt the syntax of Java Random.next() method, and also learnt how to use this method with the help of examples.