Random value

In this chapter you will learn:

  1. How to generate random integers
  2. How to generate random double
  3. How to seed a random generator

Random integers

Call nextInt() to get random integers

import java.util.Random;
//from   j ava2s. c  o  m
public class MainClass {

  public static void main(String args[]) {

    Random generator = new Random();

    for(int i = 0; i < 10; i++)
      System.out.println(generator.nextInt());
  }
}

The code above generates the following result.

Random double

call nextDouble() to get next random double value

import java.util.Random;
/*ja  v  a  2  s . c om*/
public class MainClass {

  public static void main(String args[]) {
    Random rand = new Random();
    System.out.println(rand.nextDouble());
  }
}

The code above generates the following result.

Seed a random

The next example creates Random class from an Integer using new Random(int intValue).

import java.util.Random;
//from j  a  v  a  2  s . com
public class MainClass {

  public static void main(String args[]) {
    Random generator = new Random(100);

    System.out.println("First generator:");
    for(int i = 0; i < 10; i++)
      System.out.println(generator.nextInt());

  }
}

Output:

Next chapter...

What you will learn in the next chapter:

  1. How to generate random value between 0 and 1
  2. How to generate random value in a range
Home » Java Tutorial » Utility Classes
Java standard stream
Java system property get and set
Current time in millis second and nano second
Random UUID
JVM memory
JVM garbage collector
JVM shutting down
Processor count
OS system commands
Random class
Random value
Random value range
Compile Java source code
Timer and TimerTask