Random class
In this chapter you will learn:
- Get to know the Random class
- What are the methods available for generating random numbers
- How random number to shuffle an array
Random class
The Random class is a generator of pseudorandom numbers.
Random defines the following constructors:
Random( )
creates a number generator that uses the current time as the starting, or seed, value.Random(long seed)
specify a seed value manually.
A seed defines the starting point for the random sequence. If you use the same seed to initialize another Random object, you will get the same random sequence. If you want to generate different sequences, specify different seed values.
Using the current time to seed a Random object reduces the possibility of getting repeated sequences.
methods for random values
We can call the following methods to generate random values.
boolean nextBoolean( )
Returns the next boolean random number.void nextBytes(byte vals[ ])
Fills vals with randomly generated values.double nextDouble( )
Returns the next double random number.float nextFloat( )
Returns the next float random number.double nextGaussian( )
Returns the next Gaussian random number.int nextInt( )
Returns the next int random number.int nextInt(int n)
Returns the next int random number within the range zero to n.long nextLong( )
Returns the next long random number.void setSeed(long newSeed)
Sets the seed value (starting point for the random number generator).
Random Boolean values are available from nextBoolean( )
.
Random bytes can be obtained by calling nextBytes( )
.
Integers can be extracted via the nextInt( )
method.
Long integers can be obtained with nextLong( )
.
The nextFloat( )
and nextDouble( )
methods return a
uniformly distributed float and double, respectively, between 0.0
and 1.0
.
nextGaussian( )
returns a double value centered at 0.0
with a
standard deviation of 1.0
.
Random shuffle an array
The following code shuffles an array of integers.
import java.util.Random;
//from j a v a 2s. c om
public class Main {
public static void main(String[] args) {
Random r = new Random();
int[] array = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
for (int i = 0; i < array.length; i++) {
int n = r.nextInt(array.length);
int temp = array[i];
array[i] = array[n];
array[n] = temp;
}
for (int i = 0; i < array.length; i++){
System.out.print(array[i] + " ");
}
System.out.println();
}
}
Output:
Next chapter...
What you will learn in the next chapter: