Menu
Topics Index
...
`

Random - Java Example Program


Random
import java.util.Random;

class RandomTest
{
    public static void main(String arg[])
    {
        Random r = new Random();
        
        System.out.println("The next Integer value : " + r.nextInt()); // LINE A
        System.out.println("The next Boolean value : " + r.nextBoolean());
        
        byte[] b = new byte[30];
        r.nextBytes(b); // Puts the next byte in array
        System.out.println("Value of Byte array : " + b);
        
        System.out.println("The next Double value : " + r.nextDouble());
        System.out.println("The next Float value : " + r.nextFloat());
        System.out.println("The next Gaussian value : " + r.nextGaussian());
        System.out.println("The next Integer  value between 0 to 4 : " + r.nextInt(5));
        System.out.println("The next Long value : " + r.nextLong());
        r.setSeed(20);
        System.out.println("The set Seed value : " + r.nextInt());
    
    }
}
OUTPUT

The next Integer value : 1129872169
The next Boolean value : true
Value of Byte array : [B@103074e
The next Double value : 0.47766930003831065
The next Float value : 0.13917398
The next Gaussian value : 0.8715938816913958
The next Integer  value between 0 to 4 : 1
The next Long value : 3604397887200514771
The set Seed value : -1150867590

DESCRIPTION

In this program, a random object is created and respective Integer, Boolean, Byte, Double, Float, Gaussian, Long values are generated. Note that when you run the program, the same output might not come. For every run the output will be different.

THINGS TO TRY
  • In the nextInt method, replace 3 in place of 5 to get the output of integer range in between 0 to 2.
  • After LINE A, call nextInt multiple times and see that different integers are returned for multiple calls.

© meritcampus 2019

All Rights Reserved.

Open In App