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,

RandomNumberTest.java

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();
System.out.println(randomValue);

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;
System.out.println(randomValue);

Comments

comments

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Comments

  1. I am often to blogging and i really respect your content. The article has really peaks my interest. I am going to bookmark your website and keep checking for new information.

Speak Your Mind

*