Generation of Random Numbers

Random numbers in java can be generated either by using the Random class in java.util package or by using the random() method in the Math class in java.lang package.

also read:

In both these approaches, we only get a pseudo random number and not a true random number because it is all generated based on some mathematical computation, and hence the number can be predicted if the logic behind the computation is known. In spite of this, we can use any of these two approaches itself for random number generation for most of our application needs.

Using the Random class

The Random class in java.util package can be used in order to generate random numbers. A seed value can be specfied, which would be used for generating random numbers. This seed value can be specified while creating the Random object. If it is not specified, then the default seed value would be the current time in a day.

There are several methods such as next(), nextInt(), nextDouble(), nextFloat(), nextLong(), nextBytes(), nextBoolean() and nextGaussian() etc.. which can be used to generate random numbers of different data types.

Let us see a simple example for generating random numbers using the Random class,

import java.util.Random;

public class RandomNumberTest {

    public static void main(String[] args) {

        Random random = new Random();
        int randomVal1 = random.nextInt();
        long randomVal2 = random.nextLong();
        float randomVal3 = random.nextFloat();
        System.out.println(randomVal1 + "n"  + randomVal2+ "n"  + randomVal3);

The above code would generate random int, long and float values.

Using the random() method in Math class

The random() method in Math class returns a random positive decimal value that ranges between 0.0 and 1.0. It is a static synchronized method.

The following code shows how to generate random numbers using the random() method,

double randomValue = Math.random();

If we need to generate a random number in a particular range, we can do so by using the following syntax,

<lower-bound in the range> + Math.random() * <count of numbers in the range>

The following code is an example of generating random numbers within a range of 10 to 15,

double randomValue = 10 + Math.random() * 5;

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

Pin It on Pinterest

Share This

Share this post with your friends!

Share This

Share this post with your friends!