Random Class In java.util Package

Introduction

The Random class is a generator of pseudorandom numbers. These are called pseudorandom numbers because they are simply uniformly distributed sequences.

Constructors uses

Random defines the following constructors,

  • Random()
  • Random(long seed)

The first constructor creates a number generator that uses the current time as the starting value or seed value. The second form allows the user to specify a seed value manually. If the user initializes a Random object with a seed, then he/she can define the starting point for the random sequence. If the user uses the same seed to initialize another Random object, the user has to extract the same random sequence,
To generate different sequences, different seed values have to be specified. The easiest way to do is to use the current time to seed a Random object, thus reducing the possibility of getting repeated sequences.

Methods define by Random class

Boolean nextBoolean()

This method returns the next Boolean random number.

void nextBytes(byte vals[])

This method fills vals with randomly generated values.

int nextLong()

This method returns the next long random number.

void setTime(long time)

Sets the time and date as specified by time , which represents the time elapsed in milliseconds from midnight.

void setSeed(long newSeed)

This method sets the seed value.

For example,

Open a new file in the editor and type the following code:

import java.util.Random;
class RandomDemo {
    public static void main(String args[]) {
        Random r = new Random();
        double sum = 0;
        double val;
        int bell[] = new int[10];
        for (int i = 0; i < 100; i++) {
            val = r.nextGaussian();
            sum += val;
            double t = -2;
            for (int x = 0; x < 10; x++, t += 0.5)
                if (val < t) ++
            bell[x++];
            break;
        }
        System.out.println("Average of all the value is: " + (sum / 100));
        for (int i = 0; i < 10; i++) {
            for (int x = bell[i]; x > 0; x--) System.out.print("*");
            System.out.println();
        }
    }
}
  • Save the file as RandomDemo.java
  • Compile the file using javac RandomDemo.java
  • Run the file using java RandomDemo

Summary

The Random class is a generator of pseudorandom numbers. These are called pseudorandom numbers.