Random

# Java random number generator Example

Java provides us the opportunity to generate pseudo-random numbers by using a random object generator (Random class). We will look at the below ways in this article:

• by using `Math.random()`
• by using `Random`
• by using `ThreadLocalRandom`

## 1. Usage of Math.random()

Java provides us `Math` class, which includes methods with basic numeric operations such as logarithm, square root, etc. One of these methods is `random()`, which gives a pseudo-random positive double number greater than or equal to 0.0 and less than 1.0 – [0.0, 1.0). Let us look at an example for `Math.random`

MathRandomClass
```public class MathRandomClass {
public static void main(String[] args) {
// a simple random number
double x = Math.random();
System.out.println("Double between 0.0 and 1.0: x = "+x);

// double between [0.0, 20.0)
double y = Math.random()*20.0;
System.out.println("Double between 0.0 and 20.0: y = "+y);

// integer between [3,7]
int r1 = (int) (Math.random()*5)+3;
System.out.println("Integer between 3 and 8: r1 = "+r1);

// integer between [-10,10) - maximum 9
int r2 = (int) (Math.random()*20)-10;
System.out.println("Integer between -10 and 10: r2 = "+r2);
}
}
```
```Double between 0.0 and 1.0: x = 0.2279522034933904
Double between 0.0 and 20.0: y = 7.725249419817002
Integer between 3 and 8: r1 = 3
Integer between -10 and 10: r2 = -2
```

## 2. Usage of Random

An instance of `Random` class is used to generate a stream of pseudorandom numbers.

The random class creates an instance of a random object generator.

If two instances of `Random` are created with the same seed, and the same sequence of method calls is made for each, they will generate and return identical sequences of numbers. Let us look at an example to understand the `Random` class.RandomNumberClass

```import java.util.Random;

public class RandomNumberClass {

public static void main(String[] args) {

Random generateRand = new Random();

System.out.println("Generate random numbers:");
for(int i=0; i<3; i++){
System.out.printf("%d ",generateRand.nextInt());
System.out.println(" "+generateRand.nextDouble());
}

//set ranges
Random generateRange = new Random();

System.out.println("\nGenerate random int [1,10] and double [0.0,360.0):");
// by default, nextInt(int bound) returns pseudorandom int value between 0 (inclusive) and specified bound value (exclusive)
for(int i=0; i<5; i++) {
int num = generateRange.nextInt(10)+1;
double angle = generateRange.nextDouble()*360.0;
System.out.println(" num = "+num+" and angle = "+angle);
}

Random generateGaus = new Random();
System.out.println("\nGaussian random =  "+generateGaus.nextGaussian()+"\n");

Random seed1 = new Random(5);
for(int i=0; i<3; i++) {
System.out.println("seed1 = "+seed1.nextInt());
}
System.out.println("--------------------");
Random seed2 = new Random(5);
for(int i=0; i<3; i++) {
System.out.println("seed2 = "+seed2.nextInt());
}
}
}
```

We use `nextInt()` and `nextDouble()` methods to generate int and double random values respectively. The `nextInt()` method will return a pseudorandomly generated int value that would be in all possible int ranges of 2^32. The `nextDouble()` function generates double numbers between 0.0 and 1.0.

Also, we can produce random numbers from a specific range. We have to set the appropriate numbers or/and make some operations (multiply/add). In our example, we want to produce random integer numbers that belong to [1,10] range. The`nextInt(n)` returns a random between 0 (inclusive) and the specified value `n` (exclusive). Hence `nextInt(10)` +1 is used. The nextDouble() does not have such ranges. Hence, we should multiply/add the returned random with the appropriate values. As you can see in the code above, we want to produce angles – the range is [0.0, 360.0) – so we multiply with the double 360.0.

The `Random` class contains `nextGaussian()`, that returns the next pseudorandom distributed double number with mean 0.0 and standard deviation 1.0.

In the above example, we initialized two instances of `Random` class with the same seed. As explained above, the `seed1` sequence will be identical to the sequence of `seed2`. So, if the seed is known we can find out which numbers are going to be generated in a specific algorithm and this can be very important information for some apps.

Now you can see the output of the above execution. Please, notice that the random values are contained in the respective ranges. Also, we can ascertain that the sequence of the instances `seed1` and `seed2` are the same.

Output

```Generate random numbers:
-906587502  0.47291343028193733
1282976872  0.9810376969317285
-1650541178  0.47312499538673947

Generate random int [1,10] and double [0.0,360.0):
num = 8 and angle = 29.3332477431203
num = 6 and angle = 114.05670201967776
num = 6 and angle = 140.71230065866766
num = 7 and angle = 354.5249452932836
num = 10 and angle = 159.76422587013093

Gaussian random =  0.9854270231907662

seed1 = -1157408321
seed1 = 758500184
seed1 = 379066948
--------------------
seed2 = -1157408321
seed2 = 758500184
seed2 = 379066948
```

The ThreadLocalRandom class generates a random number isolated to the current thread. Like the global `Random` generator used by the `Math` class, a `ThreadLocalRandom` is initialized with an internally generated seed that may not otherwise be modified. When applicable, use of `ThreadLocalRandom` rather than shared `Random` objects in concurrent programs will typically encounter much less overhead and contention.

Usages of this class should typically be of the form: `ThreadLocalRandom.current().nextX(...)` (where `X` is `Int``Long`, etc). When all usages are of this form, it is never possible to accidentally share a `ThreadLocalRandom` across multiple threads.

Let us look at an example using `ThreadLocalRandom`ThreadLocalRandomClass

```import java.util.concurrent.ThreadLocalRandom;

public static void main(String[] args) {

System.out.println("Generate random numbers:");
for(int i=0; i<3; i++){
System.out.printf("%d ",generateRand.nextInt());
System.out.println(" "+generateRand.nextDouble());
}
System.out.println("\nGenerate random int [2,10):");
// by default, nextInt(int bound) returns pseudorandom int value between 0 (inclusive) and specified bound value (exclusive)
for(int i=0; i<5; i++) {
int num = generateRand.nextInt(2,10);

System.out.println(" num = "+num);
}

}
}
```

The output would be as below:

```Generate random numbers:
1917514405  0.6619368921297559
-1426595768  0.4106713198247198
1457311547  0.9200186801029826

Generate random int [2,10):
num = 3
num = 3
num = 4
num = 2
num = 7
```

## 4. Usage of these classes

We need to consider the below when using the classes discussed.

• `Math.random()`: Many applications will find the method `Math.random()` simpler to use. The method is properly synchronized to allow correct use by more than one thread. However, if many threads need to generate pseudorandom numbers at a great rate, it may reduce contention for each thread to have its own pseudorandom-number generator. `Math.random()` internally uses the `Random` class. `Math.random()` also requires about twice the processing and is subject to synchronization.
• `Random`: The algorithms implemented by class `Random` use a protected utility method that on each invocation can supply up to 32 pseudorandomly generated bits. Instances of `Random` class are threadsafe. However concurrent use of the same instance across threads may encounter contention.
• `ThreadLocalRandom`: Use this class in multi-threaded designs.

This was a tutorial about random number generator in Java.
Download the source code of this example: Java random number generator Example

Last updated on May 05th, 2021

### Venkat-Raman Nagarajan

Venkat works for a major IT firm in India and has more than a decade of experience working and managing Java projects for a banking client.
Subscribe
Notify of This site uses Akismet to reduce spam. Learn how your comment data is processed.