Generate random numbers in Java

In this tutorial we will use the java.util.Random class and then write code to generate 10 random number between 0 and 1000.

Generate random numbers in Java

In this tutorial we will use the java.util.Random class and then write code to generate 10 random number between 0 and 1000.

Generate random numbers in Java

Generate random numbers in Java - How to use the java.util.Random class to generate desired random number in Java program?

In this tutorial I will teach you how to write Java code using the java.util.Random class to generate single or a set of random numbers in your program.

We are using the java.util.Random class for generating the random number. Random class is an utility class in Java which is used by developers to generate pseudo-random numbers in the Java programming language. The instance of this class is thread-safe and can be used generate random numbers efficiently. But if you are using this class in cryptography environment then its instance is cryptographically insecure. This class is flexible and it is used for generating random float, double, int values.

Constructors:

Let's see the constructor of this class:

Random(): This constructor is used to create an instance of random number generator class.

Random(long seed): This constructor is used to create random number generator class a single long seed

We are using the randomGenerator.nextInt(num) method to generate the random number. The java.util.Random class is used to generate the random integers, doubles, int etc..

Following code can be used to generate a random number between 0,1000:

int randomInt = randomGenerator.nextInt(1000);

Following is the code to generate 10 random number between 0 and 1000:

import java.util.Random;

/** Example of Random Number generation in Java*/
public final class RandomGenerator {
  
  public static final void main(String... aArgs){
    
    Random randomGen = new Random();
    for (int idx = 1; idx <= 10; ++idx){
      int randomInt = randomGen.nextInt(1000);
      System.out.println("Generated Number: " + randomInt);
    }
    
  }
}

If you run the above code following output will be displayed on the browser:

Generate Random Number in Java

Check more Tutorials

We have tutorials of many Java programming in our website. Check these related tutorials.