Pavlo Plynko
Java Developer at CodeGym

# Java Math.random() Method

## What is Math.random() Method in Java?

The java.lang.Math.random() method returns a pseudorandom, “double” type number ranging from 0.0 to 1.0.
Hence, the random number generated with the built-in method by Java always lies between 0 and 1.
``````
0.0 ≤ random < 1.0
``````
Kindly note, that the random number is greater than or equal to 0.0 and less than 1.0.

## How to Use Math.random() in Java?

Using the Math.random() method is pretty simple even for beginners.

### Example 1

Let’s look at a basic example for a clear understanding.
``````
public class RandomTest {

public static void main(String[] args) {

double random1 = Math.random();
double random2 = Math.random();

System.out.println("First Random Number: " + random1);
System.out.println("Second Random Number: " + random2);
}
}
``````

#### Output

First Random Number: 0.5486939400685561 Second Random Number: 0.23550115674999972

## Using random() Method within a Range

Calling Math.random() method looks pretty self-explanatory. However, our need for random numbers doesn’t always lie within the range of 0 and 1. For real-life problems, we can operate within other specified ranges as well. Let’s look at an example of using the Math.random() method for a given range, say 1 to 50.

### Example 2

``````
public class RandomNumberInRange {
public static int getRandom(int min, int max) {

int range = (max - min) + 1;
int random = (int) ((range * Math.random()) + min);
return random;
}

public static void main(String[] args) {
// Let's play Ludo with 4 Players
int dieRoll = getRandom(1, 6);
System.out.println("Red's Turn: " + dieRoll);

dieRoll = getRandom(1, 6);
System.out.println("Blue's Turn: " + dieRoll);

dieRoll = getRandom(1, 6);
System.out.println("Green's Turn: " + dieRoll);

dieRoll = getRandom(1, 6);
System.out.println("Yellow's Turn: " + dieRoll);
}
}
``````

#### Output

Red's Turn: 3 Blue's Turn: 2 Green's Turn: 6 Yellow's Turn: 4

### Explanation

To get a random number within a range, you need to calculate the range by subtracting min from max. Then after taking a product of range with the Math.rand() you need to add the min number. After casting the double to an int, you have your random number within the specified range.

## Conclusion

By the end of this post, we hope you have got yourself familiarized with the Math.random() method in Java. Keep practising for a deeper command of the concept. Till then, keep growing and keep shining!