The `java.lang.Math.random()`

method returns random number between `0.0`

and `1.0`

including `0.0`

but not including `1.0`

. By multiplying `Math.random()`

result with a number, for example `10`

will give us a range of random number between `0.0`

and `10.0`

.

To get a random number between two numbers (`n`

and `m`

) we can use the formula of: `n + (Math.random() * (m - n))`

. Where `n`

is the lowest number (inclusive) and `m`

is the highest number (exclusive).

```
package org.kodejava.example.lang;
public class RandomNumberExample {
public static void main(String[] args) {
// The Math.random() returns a random number between 0.0 and 1.0
// including 0.0 but not including 1.0.
double number = Math.random();
System.out.println("Generated number: " + number);
// By multiplying Math.random() result with a number will give
// us a range of random number between, for instance 0.0 to 10.0 as
// shown in the example below.
number = Math.random() * 10;
System.out.println("Generated number: " + number);
// To get a random number between n and m we can use the formula:
// n + (Math.random() * (m - n)). The example below creates random
// number between 100.0 and 200.0.
int n = 100;
int m = 200;
number = n + (Math.random() * (m - n));
System.out.println("Generated number: " + number);
// Creates an integer random number
int random = 100 + (int) (Math.random() * 100);
System.out.println("Generated number: " + random);
}
}
```

Here is an example result of our program.

```
Generated number: 0.670447515721026
Generated number: 5.118459516569203
Generated number: 139.89504952544274
Generated number: 158
```

Latest posts by Wayan Saryada (see all)

- How do I convert java.util.TimeZone to java.time.ZoneId? - April 25, 2020
- How do I get a list of all TimeZones Ids using Java 8? - April 25, 2020
- How do I get HTTP headers using HttpClient HEAD request? - April 22, 2020

Thank you very much! It’s helpful.