Random numbers in java can be generated either by using the * Random* class in

`java.util`

package or by using the *method in the*

**random()**`Math`

class in `java.lang`

package.

also read:

- Java Tutorials
- Java EE Tutorials
- Design Patterns Tutorials
- Java File IO Tutorials

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**

[code lang=”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);

}

}

[/code]

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,

[code lang=”java”]

double randomValue = Math.random();

System.out.println(randomValue);

[/code]

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

[code]

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

[/code]

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

[code lang=”java”]

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

System.out.println(randomValue);

[/code]

## Leave a Reply