java

How to generate random numbers in Java

In this tutorial, we are going to see how to generate a random number using Java’s Random class and the Math.Random method.
 

Generate a random number using Java

Java provides interesting ways to generate random numbers, not only for scientific calculations but also for other applications, such as creating a unique session ID on a web server, cryptography, security, math, etc.

There are two ways to do this:

  • Use of the Random class (in the java.util package).
  • Using the Math.Random java class (however, this will generate a double between 0.0 and 1.0).
 

Example: using the Random class

Suppose we need to generate 10 random numbers between 0 and 100.

import java.util.Random;

public class RandomNbr{
    public static void main(String[] args) {
         Random obj = new Random();
         for (int i = 0; i < 10; i++){
             int nbr = obj.nextInt(100);
             System.out.println("Random number : " + nbr); 
         }
    }
}

An object of the Random class is initialized as “obj”. The Random class has the “nextInt” method. This will provide a random number based on the argument specified as the upper limit, while the lower limit is set to 0. This will result in 10 random numbers displayed.
 

Example: using Math.Random

The Math class contains several methods for performing various numerical operations, such as calculating the exponential, logarithms, etc. One of these methods is random(). This method returns a double value greater than or equal to 0.0 and less than 1.0. The returned values are chosen in a pseudo-random manner. This method can only generate random numbers of type Doubles. The following program explains how to use this method:

public class RandomNbr{
     public static void main(String[] args) {
          for(int i = 0; i < 10; i++){
               System.out.println(Math.random());
          }
     }
}

 

Conclusion

The java.util.Random class implements what is generally called a linear congruence generator (GCL). It is designed to be fast but does not meet the requirements of real-time use. For example, use in scientific calculations, cryptography, etc.
 

mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *