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

### Wayan

Programmer, runner, recreational diver, live in the island of Bali, Indonesia. Mostly programming in Java, Spring Framework, Hibernate / JPA. Support me, buy me ☕ or 🍵

#### Latest posts by Wayan (see all)

- How do I set the default Java (JDK) version on Mac OS X? - November 14, 2017
- A User Interface is Like a Joke - November 10, 2017
- How do I pass password to sudo commands? - October 17, 2017

Thank you very much! It’s helpful.