Java Random class

Introduction

We can use Java Random class to create random values.

The following code generates random Gaussian values.



// Demonstrate random Gaussian values.
import java.util.Random;

public class Main {
  public static void main(String args[]) {
    Random r = new Random();
    double sum = 0;

    for (int i = 0; i < 100; i++) {
      double val = r.nextGaussian();
      sum += val;
    }//from ww w  .  j  av  a  2  s.  c  o  m
    System.out.println("Average of values: " + (sum / 100));

  }
}

import java.util.Random;

public class Main {

   public static void main(String[] args) {
      // Create a new instance of the Random class
      Random random = new Random();

      // Generates a random Integer
      int myInt = random.nextInt();
      System.out.println(myInt);/*from   w ww  .j  ava2  s.  co  m*/
      // Generates a random Double value
      double myDouble = random.nextDouble();
      System.out.println(myDouble);
      // Generates a random float
      float myFloat = random.nextFloat();
      System.out.println(myFloat);
      // Generates a random Gaussian double
      // mean 0.0 and standard deviation 1.0
      // from this random number generator's sequence.
      double gausDouble = random.nextGaussian();
      System.out.println(gausDouble);
      // Generates a random Long
      long myLong = random.nextLong();
      System.out.println(myLong);
      // Generates a random boolean
      boolean myBoolean = random.nextBoolean();
      System.out.println(myBoolean);

      double rand = Math.random();
      System.out.println(rand);
   }
}



PreviousNext

Related