Java Basic Examples

# Generate Random Number using random method of Java Math class

This example shows how to generate random numbers using random() method of Java Math class.

## How to generate random numbers in Java?

Use random() static method of Java Math class to generate random number in Java.

This method returns a double number greater than or equal to 0.0 and less than 1.0 (Note that 0.0 is inclusive while 1.0 is exclusive so that 0 <= n < 1)

### a) Generate random number between 0 and 1

Output (could be different for you as these are random numbers)

### b) Generate random numbers between 0 and 100

It is fairly easy task to generate random numbers between 0 and 100. Since random() method returns a number between 0.0 and 1.0, multiplying it with 100 and casting the result to integer will give us random number between 0 and 100 (where 0 is inclusive while 100 is exclusive).

### c) Generate random numbers in specific range

Since Math.random() returns double value between 0.0 and 1.0, we need to derive a formula so that we can generate random numbers in the specific range.

Let’s do that step by step. Suppose you want to generate random numbers between 10 and 20. So minimum number it should generate is 10 and maximum number should be 20.

#### Step 1:

First of all we need to multiply Math.random() result with the maximum number so that it returns value between 0 to max value (in this case 20) like given below.

The above statement will return us a random number between 0.0 and 19. That is because multiplying 0.0 – 0.99 with 20 and casting the result back to int will give us range of 0 to 19.

#### Step 2:

Step 1 gives us a random number between 0 and 19. But we want random number starting from 10 not 0. Let’s add that number to the result.

#### Step 3:

Now the number starts from 10 but it goes up to 30. That is because adding 10 to 0-19 will give us 10-29. So let’s subtract 10 from 20 before multiplication operation.

#### Step 4:

Random number generated by above formula gives us range between 10 and 19 (both inclusive). The number range we wanted was between 10 and 20 (both inclusive). So let’s add 1 to the equation.

The final result is a random number in the range of 10 to 20.

## General formula to generate random number in specific range

Formula to generate random number in the range of min and max is,

Final example to generate random number in specific range is given below.

Want to learn quickly?
Try one of the many quizzes. I promise you will not be disappointed.

Tags